home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / bash_114.zip / bash-1.14.2 / subst.c < prev    next >
C/C++ Source or Header  |  1994-08-09  |  116KB  |  4,722 lines

  1. /* subst.c -- The part of the shell that does parameter, command, and
  2.    globbing substitutions. */
  3.  
  4. /* Copyright (C) 1987,1989 Free Software Foundation, Inc.
  5.  
  6.    This file is part of GNU Bash, the Bourne Again SHell.
  7.  
  8.    Bash is free software; you can redistribute it and/or modify it under
  9.    the terms of the GNU General Public License as published by the Free
  10.    Software Foundation; either version 2, or (at your option) any later
  11.    version.
  12.  
  13.    Bash is distributed in the hope that it will be useful, but WITHOUT ANY
  14.    WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15.    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16.    for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License along
  19.    with Bash; see the file COPYING.  If not, write to the Free Software
  20.    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  21.  
  22. #include "bashtypes.h"
  23. #include <stdio.h>
  24. #include <pwd.h>
  25. #include <signal.h>
  26. #include <errno.h>
  27. /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
  28. #if !defined (errno)
  29. extern int errno;
  30. #endif /* !errno */
  31.  
  32. #include "bashansi.h"
  33. #include "posixstat.h"
  34.  
  35. #include "shell.h"
  36. #include "flags.h"
  37. #include "jobs.h"
  38. #include "execute_cmd.h"
  39. #include "filecntl.h"
  40.  
  41. #if defined (READLINE)
  42. #  include <readline/readline.h>
  43. #else
  44. #  include <tilde/tilde.h>
  45. #endif
  46.  
  47. #if defined (HISTORY)
  48. #  include "bashhist.h"
  49. #  include <readline/history.h>
  50. #endif
  51.  
  52. #include <glob/fnmatch.h>
  53.  
  54. /* The size that strings change by. */
  55. #define DEFAULT_ARRAY_SIZE 512
  56.  
  57. /* How to quote and determine the quoted state of the character C. */
  58. static char *make_quoted_char ();
  59. #define QUOTED_CHAR(c)  ((c) == CTLESC)
  60.  
  61. /* Process ID of the last command executed within command substitution. */
  62. pid_t last_command_subst_pid = NO_PID;
  63.  
  64. /* Extern functions and variables from different files. */
  65. extern int last_command_exit_value, interactive, interactive_shell;
  66. extern int subshell_environment;
  67. extern int dollar_dollar_pid, no_brace_expansion;
  68. extern int posixly_correct;
  69. extern int opterr, optind;
  70. extern int eof_encountered, eof_encountered_limit, ignoreeof;
  71. extern char *this_command_name;
  72. extern jmp_buf top_level;
  73. #if defined (READLINE)
  74. extern int no_line_editing;
  75. extern int hostname_list_initialized;
  76. #endif
  77.  
  78. #if !defined (USE_POSIX_GLOB_LIBRARY)
  79. extern int glob_dot_filenames, noglob_dot_filenames;
  80. extern char *glob_error_return;
  81. #endif
  82.  
  83. static WORD_LIST expand_word_error, expand_word_fatal;
  84. static char expand_param_error, expand_param_fatal;
  85.  
  86. static WORD_LIST *expand_string_internal ();
  87. static WORD_LIST *expand_word_internal (), *expand_words_internal ();
  88. static WORD_LIST *expand_string_leave_quoted ();
  89. static WORD_LIST *word_list_split ();
  90. static char *quote_string ();
  91. static int unquoted_substring (), unquoted_member ();
  92. static int unquoted_glob_pattern_p ();
  93. static void quote_list (), dequote_list ();
  94. static int do_assignment_internal ();
  95. static char *string_extract_verbatim (), *string_extract ();
  96. static char *string_extract_double_quoted (), *string_extract_single_quoted ();
  97. static char *extract_delimited_string ();
  98. static char *extract_dollar_brace_string ();
  99.  
  100. /* **************************************************************** */
  101. /*                                    */
  102. /*            Utility Functions                */
  103. /*                                    */
  104. /* **************************************************************** */
  105.  
  106. /* Cons a new string from STRING starting at START and ending at END,
  107.    not including END. */
  108. char *
  109. substring (string, start, end)
  110.      char *string;
  111.      int start, end;
  112. {
  113.   register int len = end - start;
  114.   register char *result = xmalloc (len + 1);
  115.  
  116.   strncpy (result, string + start, len);
  117.   result[len] = '\0';
  118.   return (result);
  119. }
  120.  
  121. /* Conventions:
  122.  
  123.      A string with s[0] == CTLNUL && s[1] == 0 is a quoted null string.
  124.      The parser passes CTLNUL as CTLESC CTLNUL. */
  125.  
  126. /* The parser passes us CTLESC as CTLESC CTLESC and CTLNUL as CTLESC CTLNUL.
  127.    This is necessary to make unquoted CTLESC and CTLNUL characters in the
  128.    data stream pass through properly.
  129.    Here we remove doubled CTLESC characters inside quoted strings before
  130.    quoting the entire string, so we do not double the number of CTLESC
  131.    characters. */
  132. static char *
  133. remove_quoted_escapes (string)
  134.      char *string;
  135. {
  136.   register char *s;
  137.  
  138.   for (s = string; s && *s; s++)
  139.     {
  140.       if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL))
  141.     strcpy (s, s + 1);    /* XXX - should be memmove */
  142.     }
  143.   return (string);
  144. }
  145.  
  146. /* Quote escape characters in string s, but no other characters.  This is
  147.    used to protect CTLESC and CTLNUL in variable values from the rest of
  148.    the word expansion process after the variable is expanded. */
  149. static char *
  150. quote_escapes (string)
  151.      char *string;
  152. {
  153.   register char *s, *t;
  154.   char *result;
  155.  
  156.   result = xmalloc ((strlen (string) * 2) + 1);
  157.   for (s = string, t = result; s && *s; )
  158.     {
  159.       if (*s == CTLESC || *s == CTLNUL)
  160.     *t++ = CTLESC;
  161.       *t++ = *s++;
  162.     }
  163.   *t = '\0';
  164.   return (result);
  165. }      
  166.  
  167. /* Just like string_extract, but doesn't hack backslashes or any of
  168.    that other stuff.  Obeys quoting.  Used to do splitting on $IFS. */
  169. static char *
  170. string_extract_verbatim (string, sindex, charlist)
  171.      char *string, *charlist;
  172.      int *sindex;
  173. {
  174.   register int i = *sindex;
  175.   int c;
  176.   char *temp;
  177.  
  178.   if (charlist[0] == '\'' && !charlist[1])
  179.     return (string_extract_single_quoted (string, sindex));
  180.  
  181.   for (i = *sindex; (c = string[i]); i++)
  182.     {
  183.       if (c == CTLESC)
  184.     {
  185.       i++;
  186.       continue;
  187.     }
  188.  
  189.       if (MEMBER (c, charlist))
  190.     break;
  191.     }
  192.  
  193.   temp = xmalloc (1 + (i - *sindex));
  194.   strncpy (temp, string + (*sindex), i - (*sindex));
  195.   temp[i - (*sindex)] = '\0';
  196.   *sindex = i;
  197.  
  198.   return (temp);
  199. }
  200.  
  201. /* Extract a substring from STRING, starting at SINDEX and ending with
  202.    one of the characters in CHARLIST.  Don't make the ending character
  203.    part of the string.  Leave SINDEX pointing at the ending character.
  204.    Understand about backslashes in the string. */
  205. static char *
  206. string_extract (string, sindex, charlist)
  207.      char *string, *charlist;
  208.      int *sindex;
  209. {
  210.   register int c, i = *sindex;
  211.   char *temp;
  212.  
  213.   while (c = string[i])
  214.     {
  215.       if (c == '\\')
  216.     if (string[i + 1])
  217.       i++;
  218.     else
  219.       break;
  220.       else
  221.     if (MEMBER (c, charlist))
  222.       break;
  223.       i++;
  224.     }
  225.   temp = xmalloc (1 + (i - *sindex));
  226.   strncpy (temp, string + (*sindex), i - (*sindex));
  227.   temp[i - (*sindex)] = '\0';
  228.   *sindex = i;
  229.   return (temp);
  230. }
  231.  
  232. /* Remove backslashes which are quoting backquotes from STRING.  Modifies
  233.    STRING, and returns a pointer to it. */
  234. char *
  235. de_backslash (string)
  236.      char *string;
  237. {
  238.   register int i, l = strlen (string);
  239.  
  240.   for (i = 0; i < l; i++)
  241.     if (string[i] == '\\' && (string[i + 1] == '`' || string[i + 1] == '\\' ||
  242.                   string[i + 1] == '$'))
  243.       strcpy (string + i, string + i + 1);    /* XXX - should be memmove */
  244.   return (string);
  245. }
  246.  
  247. #if 0
  248. /* Replace instances of \! in a string with !. */
  249. void
  250. unquote_bang (string)
  251.      char *string;
  252. {
  253.   register int i, j;
  254.   register char *temp;
  255.  
  256.   temp = xmalloc (1 + strlen (string));
  257.  
  258.   for (i = 0, j = 0; (temp[j] = string[i]); i++, j++)
  259.     {
  260.       if (string[i] == '\\' && string[i + 1] == '!')
  261.     {
  262.       temp[j] = '!';
  263.       i++;
  264.     }
  265.     }
  266.   strcpy (string, temp);
  267.   free (temp);
  268. }
  269. #endif
  270.  
  271. /* Extract the $( construct in STRING, and return a new string.
  272.    Start extracting at (SINDEX) as if we had just seen "$(".
  273.    Make (SINDEX) get the position just after the matching ")". */
  274. char *
  275. extract_command_subst (string, sindex)
  276.      char *string;
  277.      int *sindex;
  278. {
  279.   return (extract_delimited_string (string, sindex, "$(", "(", ")"));
  280. }
  281.  
  282. /* Extract the $[ construct in STRING, and return a new string.
  283.    Start extracting at (SINDEX) as if we had just seen "$[".
  284.    Make (SINDEX) get the position just after the matching "]". */
  285. char *
  286. extract_arithmetic_subst (string, sindex)
  287.      char *string;
  288.      int *sindex;
  289. {
  290.   return (extract_delimited_string (string, sindex, "$[", "[", "]"));
  291. }
  292.  
  293. #if defined (PROCESS_SUBSTITUTION)
  294. /* Extract the <( or >( construct in STRING, and return a new string.
  295.    Start extracting at (SINDEX) as if we had just seen "<(".
  296.    Make (SINDEX) get the position just after the matching ")". */
  297. char *
  298. extract_process_subst (string, starter, sindex)
  299.      char *string;
  300.      char *starter;
  301.      int *sindex;
  302. {
  303.   return (extract_delimited_string (string, sindex, starter, "(", ")"));
  304. }
  305. #endif /* PROCESS_SUBSTITUTION */
  306.  
  307. /* Extract and create a new string from the contents of STRING, a
  308.    character string delimited with OPENER and CLOSER.  SINDEX is
  309.    the address of an int describing the current offset in STRING;
  310.    it should point to just after the first OPENER found.  On exit,
  311.    SINDEX gets the position just after the matching CLOSER.  If
  312.    OPENER is more than a single character, ALT_OPENER, if non-null,
  313.    contains a character string that can also match CLOSER and thus
  314.    needs to be skipped. */
  315. static char *
  316. extract_delimited_string (string, sindex, opener, alt_opener, closer)
  317.      char *string;
  318.      int *sindex;
  319.      char *opener, *alt_opener, *closer;
  320. {
  321.   register int i, c, l;
  322.   int pass_character, nesting_level;
  323.   int delimiter, delimited_nesting_level;
  324.   int len_closer, len_opener, len_alt_opener;
  325.   char *result;
  326.  
  327.   len_opener = STRLEN (opener);
  328.   len_alt_opener = STRLEN (alt_opener);
  329.   len_closer = STRLEN (closer);
  330.  
  331.   pass_character = delimiter = delimited_nesting_level = 0;
  332.  
  333.   nesting_level = 1;
  334.  
  335.   for (i = *sindex; c = string[i]; i++)
  336.     {
  337.       if (pass_character)
  338.     {
  339.       pass_character = 0;
  340.       continue;
  341.     }
  342.  
  343.       if (c == CTLESC)
  344.     {
  345.       pass_character++;
  346.       continue;
  347.     }
  348.  
  349.       if (c == '\\')
  350.     {
  351.       if ((delimiter == '"') &&
  352.           (member (string[i + 1], slashify_in_quotes)))
  353.         {
  354.           pass_character++;
  355.           continue;
  356.         }
  357.     }
  358.  
  359.       if (!delimiter || delimiter == '"')
  360.     {
  361.       if (STREQN (string + i, opener, len_opener))
  362.         {
  363.           if (!delimiter)
  364.         nesting_level++;
  365.           else
  366.         delimited_nesting_level++;
  367.  
  368.           i += len_opener - 1;
  369.           continue;
  370.         }
  371.  
  372.       if (len_alt_opener && STREQN (string + i, alt_opener, len_alt_opener))
  373.         {
  374.           if (!delimiter)
  375.         nesting_level++;
  376.           else
  377.         delimited_nesting_level++;
  378.  
  379.           i += len_alt_opener - 1;
  380.           continue;
  381.         }
  382.  
  383.       if (STREQN (string + i, closer, len_closer))
  384.         {
  385.           i += len_closer - 1;
  386.  
  387.           if (delimiter && delimited_nesting_level)
  388.         delimited_nesting_level--;
  389.  
  390.           if (!delimiter)
  391.         {
  392.           nesting_level--;
  393.           if (nesting_level == 0)
  394.             break;
  395.         }
  396.         }
  397.     }
  398.  
  399.       if (delimiter)
  400.     {
  401.       if (c == delimiter || delimiter == '\\')
  402.         delimiter = 0;
  403.       continue;
  404.     }
  405.       else
  406.     {
  407.       if (c == '"' || c == '\'' || c == '\\')
  408.         delimiter = c;
  409.     }
  410.     }
  411.  
  412.   l = i - *sindex;
  413.   result = xmalloc (1 + l);
  414.   strncpy (result, string + *sindex, l);
  415.   result[l] = '\0';
  416.   *sindex = i;
  417.  
  418.   if (!c && (delimiter || nesting_level))
  419.     {
  420.       report_error ("bad substitution: no `%s' in %s", closer, string);
  421.       free (result);
  422.       longjmp (top_level, DISCARD);
  423.     }
  424.   return (result);
  425. }
  426.  
  427. /* Extract a parameter expansion expression within ${ and } from STRING.
  428.    Obey the Posix.2 rules for finding the ending `}': count braces while
  429.    skipping over enclosed quoted strings and command substitutions.
  430.    SINDEX is the address of an int describing the current offset in STRING;
  431.    it should point to just after the first `{' found.  On exit, SINDEX
  432.    gets the position just after the matching `}'. */
  433. /* XXX -- this is very similar to extract_delimited_string -- XXX */
  434. static char *
  435. extract_dollar_brace_string (string, sindex)
  436.      char *string;
  437.      int *sindex;
  438. {
  439.   register int i, c, l;
  440.   int pass_character, nesting_level;
  441.   int delimiter, delimited_nesting_level;
  442.   char *result;
  443.  
  444.   pass_character = delimiter = delimited_nesting_level = 0;
  445.  
  446.   nesting_level = 1;
  447.  
  448.   for (i = *sindex; c = string[i]; i++)
  449.     {
  450.       if (pass_character)
  451.     {
  452.       pass_character = 0;
  453.       continue;
  454.     }
  455.  
  456.       if (c == CTLESC)
  457.     {
  458.       pass_character++;
  459.       continue;
  460.     }
  461.  
  462.       /* Backslashes quote the next character. */
  463.       if (c == '\\')
  464.     {
  465.       if ((delimiter == '"') &&
  466.           (member (string[i + 1], slashify_in_quotes)))
  467.         {
  468.           pass_character++;
  469.           continue;
  470.         }
  471.     }
  472.  
  473.       if (!delimiter || delimiter == '"')
  474.     {
  475.       if (string[i] == '$' && string[i+1] == '{')
  476.         {
  477.           if (!delimiter)
  478.         nesting_level++;
  479.           else
  480.         delimited_nesting_level++;
  481.  
  482.           i++;
  483.           continue;
  484.         }
  485.  
  486.       /* Pass the contents of old-style command substitutions through
  487.          verbatim. */
  488.       if (string[i] == '`')
  489.         {
  490.           int si;
  491.           char *t;
  492.  
  493.           si = i + 1;
  494.           t = string_extract (string, &si, "`");
  495.           i = si;
  496.           free (t);
  497.           continue;
  498.         }
  499.  
  500.       /* Pass the contents of new-style command substitutions through
  501.          verbatim. */
  502.       if (string[i] == '$' && string[i+1] == '(')
  503.         {
  504.           int si;
  505.           char *t;
  506.  
  507.           si = i + 2;
  508.           t = extract_delimited_string (string, &si, "$(", "(", ")");
  509.           i = si;
  510.           free (t);
  511.           continue;
  512.         }
  513.  
  514.       if (string[i] == '{')
  515.         {
  516.           if (!delimiter)
  517.         nesting_level++;
  518.           else
  519.         delimited_nesting_level++;
  520.  
  521.           continue;
  522.         }
  523.  
  524.       if (string[i] == '}')
  525.         {
  526.           if (delimiter && delimited_nesting_level)
  527.         delimited_nesting_level--;
  528.  
  529.           if (!delimiter)
  530.         {
  531.           nesting_level--;
  532.           if (nesting_level == 0)
  533.             break;
  534.         }
  535.         }
  536.     }
  537.  
  538.       if (delimiter)
  539.     {
  540.       if (c == delimiter || delimiter == '\\')
  541.         delimiter = 0;
  542.       continue;
  543.     }
  544.       else
  545.     {
  546.       if (c == '"' || c == '\'' || c == '\\')
  547.         delimiter = c;
  548.     }
  549.     }
  550.  
  551.   l = i - *sindex;
  552.   result = xmalloc (1 + l);
  553.   strncpy (result, string + *sindex, l);
  554.   result[l] = '\0';
  555.   *sindex = i;
  556.  
  557.   if (!c && (delimiter || nesting_level))
  558.     {
  559.       report_error ("bad substitution: no ending `}' in %s", string);
  560.       free (result);
  561.       longjmp (top_level, DISCARD);
  562.     }
  563.   return (result);
  564. }
  565.  
  566. /* Extract the contents of STRING as if it is enclosed in double quotes.
  567.    SINDEX, when passed in, is the offset of the character immediately
  568.    following the opening double quote; on exit, SINDEX is left pointing after
  569.    the closing double quote. */
  570. static char *
  571. string_extract_double_quoted (string, sindex)
  572.      char *string;
  573.      int *sindex;
  574. {
  575.   register int c, j, i;
  576.   char *temp;            /* The new string we return. */
  577.   int pass_next, backquote;    /* State variables for the machine. */
  578.  
  579.   pass_next = backquote = 0;
  580.   temp = xmalloc (1 + strlen (string) - *sindex);
  581.  
  582.   for (j = 0, i = *sindex; c = string[i]; i++)
  583.     {
  584.       /* Process a character that was quoted by a backslash. */
  585.       if (pass_next)
  586.     {
  587.       /* Posix.2 sez:
  588.  
  589.          ``The backslash shall retain its special meaning as an escape
  590.          character only when followed by one of the characters:
  591.              $    `    "    \    <newline>''.
  592.  
  593.          We handle the double quotes here.  expand_word_internal handles
  594.          the rest. */
  595.       if (c != '"')
  596.         temp[j++] = '\\';
  597.       temp[j++] = c;
  598.       pass_next = 0;
  599.       continue;
  600.     }
  601.  
  602.       /* A backslash protects the next character.  The code just above
  603.      handles preserving the backslash in front of any character but
  604.      a double quote. */
  605.       if (c == '\\')
  606.     {
  607.       pass_next++;
  608.       continue;
  609.     }
  610.  
  611.       /* Inside backquotes, ``the portion of the quoted string from the
  612.      initial backquote and the characters up to the next backquote
  613.      that is not preceded by a backslash, having escape characters
  614.      removed, defines that command''. */
  615.       if (backquote)
  616.     {
  617.       if (c == '`')
  618.         backquote = 0;
  619.       temp[j++] = c;
  620.       continue;
  621.     }
  622.  
  623.       if (c == '`')
  624.     {
  625.       temp[j++] = c;
  626.       backquote++;
  627.       continue;
  628.     }
  629.  
  630.       /* Pass everything between `$(' and the matching `)' or a quoted
  631.      ${ ... } pair through according to the Posix.2 specification. */
  632.       if (c == '$' && ((string[i + 1] == '(') || (string[i + 1] == '{')))
  633.     {
  634.       register int t;
  635.       int si;
  636.       char *ret;
  637.  
  638.       si = i + 2;
  639.       if (string[i + 1] == '(')
  640.         ret = extract_delimited_string (string, &si, "$(", "(", ")");
  641.       else
  642.         ret = extract_dollar_brace_string (string, &si);
  643.  
  644.       temp[j++] = '$';
  645.       temp[j++] = string[i + 1];
  646.  
  647.       for (t = 0; ret[t]; t++)
  648.         temp[j++] = ret[t];
  649.  
  650.       i = si;
  651.       temp[j++] = string[i];
  652.       free (ret);
  653.       continue;
  654.     }
  655.  
  656.       /* An unescaped double quote serves to terminate the string. */
  657.       if (c == '"')
  658.     break;
  659.  
  660.       /* Add the character to the quoted string we're accumulating. */
  661.       temp[j++] = c;
  662.     }
  663.   temp[j] = '\0';
  664.  
  665.   /* Point to after the closing quote. */
  666.   if (c)
  667.     i++;
  668.   *sindex = i;
  669.  
  670.   return (temp);
  671. }
  672.  
  673. /* Extract the contents of STRING as if it is enclosed in single quotes.
  674.    SINDEX, when passed in, is the offset of the character immediately
  675.    following the opening single quote; on exit, SINDEX is left pointing after
  676.    the closing single quote. */
  677. static char *
  678. string_extract_single_quoted (string, sindex)
  679.      char *string;
  680.      int *sindex;
  681. {
  682.   register int i = *sindex;
  683.   char *temp;
  684.  
  685.   while (string[i] && string[i] != '\'')
  686.     i++;
  687.  
  688.   temp = xmalloc (1 + i - *sindex);
  689.   strncpy (temp, string + *sindex, i - *sindex);
  690.   temp[i - *sindex] = '\0';
  691.  
  692.   if (string[i])
  693.     i++;
  694.   *sindex = i;
  695.  
  696.   return (temp);
  697. }
  698.  
  699. /* Return 1 if the portion of STRING ending at EINDEX is quoted (there is
  700.    an unclosed quoted string), or if the character at EINDEX is quoted
  701.    by a backslash. */
  702. int
  703. char_is_quoted (string, eindex)
  704.      char *string;
  705.      int eindex;
  706. {
  707.   int i, pass_next, quoted;
  708.   char *temp;
  709.  
  710.   for (i = pass_next = quoted = 0; i <= eindex; i++)
  711.     {
  712.       if (pass_next)
  713.     {
  714.       pass_next = 0;
  715.       if (i >= eindex)    /* XXX was if (i >= eindex - 1) */
  716.         return 1;
  717.       continue;
  718.     }
  719.       else if (string[i] == '\'')
  720.         {
  721.           i++;
  722.           temp = string_extract_single_quoted (string, &i);
  723.           free (temp);
  724.           if (i > eindex)
  725.             return 1;
  726.         }
  727.       else if (string[i] == '"')
  728.         {
  729.           i++;
  730.           temp = string_extract_double_quoted (string, &i);
  731.           free (temp);
  732.           if (i > eindex)
  733.             return 1;
  734.         }
  735.       else if (string[i] == '\\')
  736.         {
  737.           pass_next = 1;
  738.           continue;
  739.         }
  740.     }
  741.   return (0);
  742. }
  743.  
  744. #if defined (READLINE)
  745. int
  746. unclosed_pair (string, eindex, openstr)
  747.      char *string;
  748.      int eindex;
  749.      char *openstr;
  750. {
  751.   int i, pass_next, openc, c, olen;
  752.   char *temp, *s;
  753.  
  754.   olen = strlen (openstr);
  755.   for (i = pass_next = openc = 0; i <= eindex; i++)
  756.     {
  757.       if (pass_next)
  758.     {
  759.       pass_next = 0;
  760.       if (i >= eindex)    /* XXX was if (i >= eindex - 1) */
  761.         return 0;
  762.       continue;
  763.     }
  764.       else if (STREQN (string + i, openstr, olen))
  765.     {
  766.       openc = 1 - openc;
  767.       i += olen - 1;
  768.     }
  769.       else if (string[i] == '\'')
  770.     {
  771.       i++;
  772.       temp = string_extract_single_quoted (string, &i);
  773.       free (temp);
  774.       if (i > eindex)
  775.         return 0;
  776.     }
  777.       else if (string[i] == '"')
  778.     {
  779.       i++;
  780.       temp = string_extract_double_quoted (string, &i);
  781.       free (temp);
  782.       if (i > eindex)
  783.         return 0;
  784.     }
  785.       else if (string[i] == '\\')
  786.     {
  787.       pass_next = 1;
  788.       continue;
  789.     }
  790.     }
  791.   return (openc);
  792. }
  793. #endif /* READLINE */
  794.  
  795. /* Extract the name of the variable to bind to from the assignment string. */
  796. char *
  797. assignment_name (string)
  798.      char *string;
  799. {
  800.   int offset = assignment (string);
  801.   char *temp;
  802.  
  803.   if (!offset)
  804.     return (char *)NULL;
  805.   temp = xmalloc (offset + 1);
  806.   strncpy (temp, string, offset);
  807.   temp[offset] = '\0';
  808.   return (temp);
  809. }
  810.  
  811. /* Return a single string of all the words in LIST.  SEP is the separator
  812.    to put between individual elements of LIST in the output string. */
  813. static char *
  814. string_list_internal (list, sep)
  815.      WORD_LIST *list;
  816.      char *sep;
  817. {
  818.   register WORD_LIST *t;
  819.   char *result, *r;
  820.   int word_len, sep_len, result_size;
  821.  
  822.   if (!list)
  823.     return ((char *)NULL);
  824.  
  825.   /* This is nearly always called with either sep[0] == 0 or sep[1] == 0. */
  826.   sep_len = STRLEN (sep);
  827.   result_size = 0;
  828.  
  829.   for (t = list; t; t = t->next)
  830.     {
  831.       if (t != list)
  832.     result_size += sep_len;
  833.       result_size += strlen (t->word->word);
  834.     }
  835.  
  836.   r = result = xmalloc (result_size + 1);
  837.  
  838.   for (t = list; t; t = t->next)
  839.     {
  840.       if (t != list && sep_len)
  841.     {
  842.       FASTCOPY (sep, r, sep_len);
  843.       r += sep_len;
  844.     }
  845.  
  846.       word_len = strlen (t->word->word);
  847.       FASTCOPY (t->word->word, r, word_len);
  848.       r += word_len;
  849.     }
  850.  
  851.   *r = '\0';    
  852.   return (result);
  853. }
  854.  
  855. /* Return a single string of all the words present in LIST, separating
  856.    each word with a space. */
  857. char *
  858. string_list (list)
  859.      WORD_LIST *list;
  860. {
  861.   return (string_list_internal (list, " "));
  862. }
  863.  
  864. /* Return a single string of all the words present in LIST, obeying the
  865.    quoting rules for "$*", to wit: (P1003.2, draft 11, 3.5.2) "If the
  866.    expansion [of $*] appears within a double quoted string, it expands
  867.    to a single field with the value of each parameter separated by the
  868.    first character of the IFS variable, or by a <space> if IFS is unset." */
  869. char *
  870. string_list_dollar_star (list)
  871.      WORD_LIST *list;
  872. {
  873.   char *ifs = get_string_value ("IFS");
  874.   char sep[2];
  875.  
  876.   if (!ifs)
  877.     sep[0] = ' ';
  878.   else if (!*ifs)
  879.     sep[0] = '\0';
  880.   else
  881.     sep[0] = *ifs;
  882.  
  883.   sep[1] = '\0';
  884.  
  885.   return (string_list_internal (list, sep));
  886. }
  887.  
  888. /* Return the list of words present in STRING.  Separate the string into
  889.    words at any of the characters found in SEPARATORS.  If QUOTED is
  890.    non-zero then word in the list will have its quoted flag set, otherwise
  891.    the quoted flag is left as make_word () deemed fit.
  892.  
  893.    This obeys the P1003.2 word splitting semantics.  If `separators' is
  894.    exactly <space><tab><newline>, then the splitting algorithm is that of
  895.    the Bourne shell, which treats any sequence of characters from `separators'
  896.    as a delimiter.  If IFS is unset, which results in `separators' being set
  897.    to "", no splitting occurs.  If separators has some other value, the
  898.    following rules are applied (`IFS white space' means zero or more
  899.    occurrences of <space>, <tab>, or <newline>, as long as those characters
  900.    are in `separators'):
  901.  
  902.     1) IFS white space is ignored at the start and the end of the
  903.        string.
  904.     2) Each occurrence of a character in `separators' that is not
  905.        IFS white space, along with any adjacent occurrences of
  906.        IFS white space delimits a field.
  907.     3) Any nonzero-length sequence of IFS white space delimits a field.
  908.    */
  909.  
  910. /* BEWARE!  list_string strips null arguments.  Don't call it twice and
  911.    expect to have "" preserved! */
  912.  
  913. /* Is the first character of STRING a quoted NULL character? */
  914. #define QUOTED_NULL(string) ((string)[0] == CTLNUL && (string)[1] == '\0')
  915.  
  916. /* Perform quoted null character removal on STRING.  We don't allow any
  917.    quoted null characters in the middle or at the ends of strings because
  918.    of how expand_word_internal works.  remove_quoted_nulls () simply
  919.    turns STRING into an empty string iff it only consists of a quoted null. */
  920. #define remove_quoted_nulls(string) \
  921.   do { if (QUOTED_NULL (string)) string[0] ='\0'; } while (0)
  922.  
  923. /* Perform quoted null character removal on each element of LIST.
  924.    This modifies LIST. */
  925. void
  926. word_list_remove_quoted_nulls (list)
  927.      WORD_LIST *list;
  928. {
  929.   register WORD_LIST *t;
  930.  
  931.   t = list;
  932.  
  933.   while (t)
  934.     {
  935.       remove_quoted_nulls (t->word->word);
  936.       t = t->next;
  937.     }
  938. }
  939.  
  940. /* This performs word splitting and quoted null character removal on
  941.    STRING. */
  942.  
  943. #define issep(c)    (member ((c), separators))
  944. #define spctabnl(c)    ((c) == ' '|| (c) == '\t' || (c) == '\n')
  945.  
  946. WORD_LIST *
  947. list_string (string, separators, quoted)
  948.      register char *string, *separators;
  949.      int quoted;
  950. {
  951.   WORD_LIST *result = (WORD_LIST *)NULL;
  952.   char *current_word = (char *)NULL, *s;
  953.   int sindex = 0;
  954.   int sh_style_split;
  955.  
  956.   if (!string || !*string)
  957.     return ((WORD_LIST *)NULL);
  958.  
  959.   sh_style_split =
  960.     separators && *separators && (STREQ (separators, " \t\n"));
  961.  
  962.   /* Remove sequences of whitespace at the beginning of STRING, as
  963.      long as those characters appear in IFS.  Do not do this if
  964.      STRING is quoted or if there are no separator characters. */
  965.   if (!quoted || !separators || !*separators)
  966.     {
  967.       for (s = string; *s && spctabnl (*s) && issep (*s); s++);
  968.  
  969.       if (!*s)
  970.     return ((WORD_LIST *)NULL);
  971.  
  972.       string = s;
  973.     }
  974.  
  975.   /* OK, now STRING points to a word that does not begin with white space.
  976.      The splitting algorithm is:
  977.          extract a word, stopping at a separator
  978.          skip sequences of spc, tab, or nl as long as they are separators
  979.      This obeys the field splitting rules in Posix.2. */
  980.  
  981.   while (string[sindex])
  982.     {
  983.       current_word = string_extract_verbatim (string, &sindex, separators);
  984.       if (!current_word)
  985.     break;
  986.  
  987.       /* If we have a quoted empty string, add a quoted null argument.  We
  988.      want to preserve the quoted null character iff this is a quoted
  989.      empty string; otherwise the quoted null characters are removed
  990.      below. */
  991.       if (QUOTED_NULL (current_word))
  992.     {
  993.       WORD_DESC *t = make_word (" ");
  994.       t->quoted++;
  995.       free (t->word);
  996.       t->word = make_quoted_char ('\0');
  997.       result = make_word_list (t, result);
  998.     }
  999.       else if (strlen (current_word))
  1000.     {
  1001.       /* If we have something, then add it regardless.  However,
  1002.          perform quoted null character removal on the current word. */
  1003.       remove_quoted_nulls (current_word);
  1004.       result = make_word_list (make_word (current_word), result);
  1005.       if (quoted)
  1006.         result->word->quoted = 1;
  1007.     }
  1008.  
  1009.       /* If we're not doing sequences of separators in the traditional
  1010.      Bourne shell style, then add a quoted null argument. */
  1011.  
  1012.       else if (!sh_style_split && !spctabnl (string[sindex]))
  1013.     {
  1014.       result = make_word_list (make_word (""), result);
  1015.       result->word->quoted = 1;
  1016.     }
  1017.  
  1018.       free (current_word);
  1019.  
  1020.       /* Move past the current separator character. */
  1021.       if (string[sindex])
  1022.     sindex++;
  1023.  
  1024.       /* Now skip sequences of space, tab, or newline characters if they are
  1025.      in the list of separators. */
  1026.       while (string[sindex] && spctabnl (string[sindex]) && issep (string[sindex]))
  1027.     sindex++;
  1028.  
  1029.     }
  1030.   return (REVERSE_LIST (result, WORD_LIST *));
  1031. }
  1032.  
  1033. /* Parse a single word from STRING, using SEPARATORS to separate fields.
  1034.    ENDPTR is set to the first character after the word.  This is used by
  1035.    the `read' builtin.
  1036.    XXX - this function is very similar to list_string; they should be
  1037.      combined - XXX */
  1038. char *
  1039. get_word_from_string (stringp, separators, endptr)
  1040.      char **stringp, *separators, **endptr;
  1041. {
  1042.   register char *s;
  1043.   char *current_word;
  1044.   int sindex, sh_style_split;
  1045.  
  1046.   if (!stringp || !*stringp || !**stringp)
  1047.     return ((char *)NULL);
  1048.     
  1049.   s = *stringp;
  1050.  
  1051.   sh_style_split =
  1052.     separators && *separators && (STREQ (separators, " \t\n"));
  1053.  
  1054.   /* Remove sequences of whitespace at the beginning of STRING, as
  1055.      long as those characters appear in IFS. */
  1056.   if (sh_style_split || !separators || !*separators)
  1057.     {
  1058.       for (; *s && spctabnl (*s) && issep (*s); s++);
  1059.  
  1060.       /* If the string is nothing but whitespace, update it and return. */
  1061.       if (!*s)
  1062.     {
  1063.       *stringp = s;
  1064.       if (endptr)
  1065.         *endptr = s;
  1066.       return ((char *)NULL);
  1067.     }
  1068.     }
  1069.  
  1070.   /* OK, S points to a word that does not begin with white space.
  1071.      Now extract a word, stopping at a separator, save a pointer to
  1072.      the first character after the word, then skip sequences of spc,
  1073.      tab, or nl as long as they are separators.
  1074.      
  1075.      This obeys the field splitting rules in Posix.2. */
  1076.   sindex = 0;
  1077.   current_word = string_extract_verbatim (s, &sindex, separators);
  1078.  
  1079.   /* Set ENDPTR to the first character after the end of the word. */
  1080.   if (endptr)
  1081.     *endptr = s + sindex;
  1082.  
  1083.   /* Move past the current separator character. */
  1084.   if (s[sindex])
  1085.     sindex++;
  1086.  
  1087.   /* Now skip sequences of space, tab, or newline characters if they are
  1088.      in the list of separators. */
  1089.   while (s[sindex] && spctabnl (s[sindex]) && issep (s[sindex]))
  1090.     sindex++;
  1091.  
  1092.   /* Update STRING to point to the next field. */
  1093.   *stringp = s + sindex;
  1094.   return (current_word);
  1095. }
  1096.  
  1097. #if defined (PROCESS_SUBSTITUTION)
  1098. #define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC)
  1099. #else
  1100. #define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC)
  1101. #endif
  1102.  
  1103. /* If there are any characters in STRING that require full expansion,
  1104.    then call FUNC to expand STRING; otherwise just perform quote
  1105.    removal if necessary.  This returns a new string. */
  1106. static char *
  1107. maybe_expand_string (string, quoted, func)
  1108.      char *string;
  1109.      int quoted;
  1110.      WORD_LIST *(*func)();
  1111. {
  1112.   WORD_LIST *list;
  1113.   int i, saw_quote;
  1114.   char *ret;
  1115.      
  1116.   for (i = saw_quote = 0; string[i]; i++)
  1117.     {
  1118.       if (EXP_CHAR (string[i]))
  1119.     break;
  1120.       else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"')
  1121.     saw_quote = 1;
  1122.     }
  1123.  
  1124.   if (string[i])
  1125.     {      
  1126.       list = (*func) (string, quoted);
  1127.       if (list)
  1128.     {
  1129.       ret = string_list (list);
  1130.       dispose_words (list);
  1131.     }
  1132.       else
  1133.     ret = (char *)NULL;
  1134.     }
  1135.   else if (saw_quote && !quoted)
  1136.     ret = string_quote_removal (string, quoted);
  1137.   else
  1138.     ret = savestring (string);
  1139.   return ret;
  1140. }
  1141.  
  1142. /* Given STRING, an assignment string, get the value of the right side
  1143.    of the `=', and bind it to the left side.  If EXPAND is true, then
  1144.    perform parameter expansion, command substitution, and arithmetic
  1145.    expansion on the right-hand side.  Perform tilde expansion in any
  1146.    case.  Do not perform word splitting on the result of expansion. */
  1147. static int
  1148. do_assignment_internal (string, expand)
  1149.      char *string;
  1150.      int expand;
  1151. {
  1152.   int offset = assignment (string);
  1153.   char *name = savestring (string);
  1154.   char *value = (char *)NULL;
  1155.   SHELL_VAR *entry = (SHELL_VAR *)NULL;
  1156.  
  1157.   if (name[offset] == '=')
  1158.     {
  1159.       char *temp;
  1160.  
  1161.       name[offset] = 0;
  1162.       temp = name + offset + 1;
  1163.  
  1164.       if (expand && temp[0])
  1165.     {
  1166.       if (strchr (temp, '~') && unquoted_member ('~', temp))
  1167.         temp = tilde_expand (temp);
  1168.       else
  1169.         temp = savestring (temp);
  1170.  
  1171.       value = maybe_expand_string (temp, 0, expand_string_unsplit);
  1172.       free (temp);
  1173.     }
  1174.       else
  1175.     value = savestring (temp);
  1176.     }
  1177.  
  1178.   if (value == 0)
  1179.     value = savestring ("");
  1180.  
  1181.   entry = bind_variable (name, value);
  1182.  
  1183.   if (echo_command_at_execute)
  1184.     fprintf (stderr, "%s%s=%s\n", indirection_level_string (), name, value);
  1185.  
  1186.   stupidly_hack_special_variables (name);
  1187.  
  1188.   if (entry)
  1189.     entry->attributes &= ~att_invisible;
  1190.  
  1191.   FREE (value);
  1192.   free (name);
  1193.  
  1194.   /* Return 1 if the assignment seems to have been performed correctly. */
  1195.   return (entry ? ((entry->attributes & att_readonly) == 0) : 0);
  1196. }
  1197.  
  1198. /* Perform the assignment statement in STRING, and expand the
  1199.    right side by doing command and parameter expansion. */
  1200. do_assignment (string)
  1201.      char *string;
  1202. {
  1203.   return do_assignment_internal (string, 1);
  1204. }
  1205.  
  1206. /* Given STRING, an assignment string, get the value of the right side
  1207.    of the `=', and bind it to the left side.  Do not do command and
  1208.    parameter substitution on the right hand side. */
  1209. do_assignment_no_expand (string)
  1210.      char *string;
  1211. {
  1212.   return do_assignment_internal (string, 0);
  1213. }
  1214.  
  1215. /* Most of the substitutions must be done in parallel.  In order
  1216.    to avoid using tons of unclear goto's, I have some functions
  1217.    for manipulating malloc'ed strings.  They all take INDX, a
  1218.    pointer to an integer which is the offset into the string
  1219.    where manipulation is taking place.  They also take SIZE, a
  1220.    pointer to an integer which is the current length of the
  1221.    character array for this string. */
  1222.  
  1223. /* Append SOURCE to TARGET at INDEX.  SIZE is the current amount
  1224.    of space allocated to TARGET.  SOURCE can be NULL, in which
  1225.    case nothing happens.  Gets rid of SOURCE by free ()ing it.
  1226.    Returns TARGET in case the location has changed. */
  1227. inline char *
  1228. sub_append_string (source, target, indx, size)
  1229.      char *source, *target;
  1230.      int *indx, *size;
  1231. {
  1232.   if (source)
  1233.     {
  1234.       int srclen, n;
  1235.  
  1236.       srclen = strlen (source);
  1237.       if (srclen >= (int)(*size - *indx))
  1238.     {
  1239.       n = srclen + *indx;
  1240.       n = (n + DEFAULT_ARRAY_SIZE) - (n % DEFAULT_ARRAY_SIZE);
  1241.       target = xrealloc (target, (*size = n));
  1242.     }
  1243.  
  1244.       FASTCOPY (source, target + *indx, srclen);
  1245.       *indx += srclen;
  1246.       target[*indx] = '\0';
  1247.  
  1248.       free (source);
  1249.     }
  1250.   return (target);
  1251. }
  1252.  
  1253. /* Append the textual representation of NUMBER to TARGET.
  1254.    INDX and SIZE are as in SUB_APPEND_STRING. */
  1255. char *
  1256. sub_append_number (number, target, indx, size)
  1257.      int number, *indx, *size;
  1258.      char *target;
  1259. {
  1260.   char *temp;
  1261.  
  1262.   temp = itos (number);
  1263.   return (sub_append_string (temp, target, indx, size));
  1264. }
  1265.  
  1266. /* Return the word list that corresponds to `$*'. */
  1267. WORD_LIST *
  1268. list_rest_of_args ()
  1269. {
  1270.   register WORD_LIST *list = (WORD_LIST *)NULL;
  1271.   register WORD_LIST *args = rest_of_args;
  1272.   int i;
  1273.  
  1274.   /* Break out of the loop as soon as one of the dollar variables is null. */
  1275.   for (i = 1; i < 10 && dollar_vars[i]; i++)
  1276.     list = make_word_list (make_word (dollar_vars[i]), list);
  1277.  
  1278.   while (args)
  1279.     {
  1280.       list = make_word_list (make_word (args->word->word), list);
  1281.       args = args->next;
  1282.     }
  1283.   return (REVERSE_LIST (list, WORD_LIST *));
  1284. }
  1285.  
  1286. /* Make a single large string out of the dollar digit variables,
  1287.    and the rest_of_args.  If DOLLAR_STAR is 1, then obey the special
  1288.    case of "$*" with respect to IFS. */
  1289. char *
  1290. string_rest_of_args (dollar_star)
  1291.      int dollar_star;
  1292. {
  1293.   register WORD_LIST *list = list_rest_of_args ();
  1294.   char *string;
  1295.  
  1296.   string = dollar_star ? string_list_dollar_star (list) : string_list (list);
  1297.   dispose_words (list);
  1298.   return (string);
  1299. }
  1300.  
  1301. /***************************************************
  1302.  *                           *
  1303.  *       Functions to Expand a String           *
  1304.  *                           *
  1305.  ***************************************************/
  1306. /* Call expand_word_internal to expand W and handle error returns.
  1307.    A convenience function for functions that don't want to handle
  1308.    any errors or free any memory before aborting. */
  1309. static WORD_LIST *
  1310. call_expand_word_internal (w, q, c, e)
  1311.      WORD_DESC *w;
  1312.      int q, *c, *e;
  1313. {
  1314.   WORD_LIST *result;
  1315.  
  1316.   result = expand_word_internal (w, q, c, e);
  1317.   if (result == &expand_word_error)
  1318.     longjmp (top_level, DISCARD);
  1319.   else if (result == &expand_word_fatal)
  1320.     longjmp (top_level, FORCE_EOF);
  1321.   else
  1322.     return (result);
  1323. }
  1324.  
  1325. /* Perform parameter expansion, command substitution, and arithmetic
  1326.    expansion on STRING, as if it were a word.  Leave the result quoted. */
  1327. static WORD_LIST *
  1328. expand_string_internal (string, quoted)
  1329.      char *string;
  1330.      int quoted;
  1331. {
  1332.   WORD_DESC td;
  1333.   WORD_LIST *tresult;
  1334.  
  1335.   if (!string || !*string)
  1336.     return ((WORD_LIST *)NULL);
  1337.  
  1338.   bzero (&td, sizeof (td));
  1339.   td.word = string;
  1340.   tresult = call_expand_word_internal (&td, quoted, (int *)NULL, (int *)NULL);
  1341.   return (tresult);
  1342. }
  1343.  
  1344. /* Expand STRING by performing parameter expansion, command substitution,
  1345.    and arithmetic expansion.  Dequote the resulting WORD_LIST before
  1346.    returning it, but do not perform word splitting.  The call to
  1347.    remove_quoted_nulls () is in here because word splitting normally
  1348.    takes care of quote removal. */
  1349. WORD_LIST *
  1350. expand_string_unsplit (string, quoted)
  1351.      char *string;
  1352.      int quoted;
  1353. {
  1354.   WORD_LIST *value;
  1355.  
  1356.   if (!string || !*string)
  1357.     return ((WORD_LIST *)NULL);
  1358.  
  1359.   value = expand_string_internal (string, quoted);
  1360.   if (value)
  1361.     {
  1362.       if (value->word)
  1363.     remove_quoted_nulls (value->word->word);
  1364.       dequote_list (value);
  1365.     }
  1366.   return (value);
  1367. }
  1368.  
  1369. /* Expand STRING just as if you were expanding a word, but do not dequote
  1370.    the resultant WORD_LIST.  This is called only from within this file,
  1371.    and is used to correctly preserve quoted characters when expanding
  1372.    things like ${1+"$@"}.  This does parameter expansion, command
  1373.    subsitution, arithmetic expansion, and word splitting. */
  1374. static WORD_LIST *
  1375. expand_string_leave_quoted (string, quoted)
  1376.      char *string;
  1377.      int quoted;
  1378. {
  1379.   WORD_LIST *tlist;
  1380.   WORD_LIST *tresult;
  1381.  
  1382.   if (!string || !*string)
  1383.     return ((WORD_LIST *)NULL);
  1384.  
  1385.   tlist = expand_string_internal (string, quoted);
  1386.  
  1387.   if (tlist)
  1388.     {
  1389.       tresult = word_list_split (tlist);
  1390.       dispose_words (tlist);
  1391.       return (tresult);
  1392.     }
  1393.   return ((WORD_LIST *)NULL);
  1394. }
  1395.  
  1396. /* Expand STRING just as if you were expanding a word.  This also returns
  1397.    a list of words.  Note that filename globbing is *NOT* done for word
  1398.    or string expansion, just when the shell is expanding a command.  This
  1399.    does parameter expansion, command substitution, arithmetic expansion,
  1400.    and word splitting.  Dequote the resultant WORD_LIST before returning. */
  1401. WORD_LIST *
  1402. expand_string (string, quoted)
  1403.      char *string;
  1404.      int quoted;
  1405. {
  1406.   WORD_LIST *result;
  1407.  
  1408.   if (!string || !*string)
  1409.     return ((WORD_LIST *)NULL);
  1410.  
  1411.   result = expand_string_leave_quoted (string, quoted);
  1412.  
  1413.   if (result)
  1414.     dequote_list (result);
  1415.   return (result);
  1416. }
  1417.  
  1418. /***************************************************
  1419.  *                           *
  1420.  *    Functions to handle quoting chars       *
  1421.  *                           *
  1422.  ***************************************************/
  1423.  
  1424. /* I'm going to have to rewrite expansion because filename globbing is
  1425.    beginning to make the entire arrangement ugly.  I'll do this soon. */
  1426. static void
  1427. dequote_list (list)
  1428.      register WORD_LIST *list;
  1429. {
  1430.   register char *s;
  1431.  
  1432.   while (list)
  1433.     {
  1434.       s = dequote_string (list->word->word);
  1435.       free (list->word->word);
  1436.       list->word->word = s;
  1437.       list = list->next;
  1438.     }
  1439. }
  1440.  
  1441. static char *
  1442. make_quoted_char (c)
  1443.      int c;
  1444. {
  1445.   char *temp;
  1446.  
  1447.   temp = xmalloc (3);
  1448.   temp[0] = CTLESC;
  1449.   temp[1] = c;
  1450.   temp[2] = '\0';
  1451.   return (temp);
  1452. }
  1453.  
  1454. /* Quote STRING.  Return a new string. */
  1455. static char *
  1456. quote_string (string)
  1457.      char *string;
  1458. {
  1459.   char *result;
  1460.  
  1461.   if (!*string)
  1462.     {
  1463.       result = xmalloc (2);
  1464.       result[0] = CTLNUL;
  1465.       result[1] = '\0';
  1466.     }
  1467.   else
  1468.     {
  1469.       register char *t;
  1470.  
  1471.       result = xmalloc ((strlen (string) * 2) + 1);
  1472.  
  1473.       for (t = result; string && *string; )
  1474.     {
  1475.       *t++ = CTLESC;
  1476.       *t++ = *string++;
  1477.     }
  1478.       *t = '\0';
  1479.     }
  1480.   return (result);
  1481. }
  1482.  
  1483. /* De-quoted quoted characters in STRING. */
  1484. char *
  1485. dequote_string (string)
  1486.      char *string;
  1487. {
  1488.   register char *t;
  1489.   char *result;
  1490.  
  1491.   result = xmalloc (strlen (string) + 1);
  1492.  
  1493.   if (QUOTED_NULL (string))
  1494.     {
  1495.       result[0] = '\0';
  1496.       return (result);
  1497.     }
  1498.  
  1499.   /* If no character in the string can be quoted, don't bother examining
  1500.      each character.  Just return a copy of the string passed to us. */
  1501.   if (strchr (string, CTLESC) == NULL)        /* XXX */
  1502.     {                        /* XXX */
  1503.       strcpy (result, string);            /* XXX */
  1504.       return (result);                /* XXX */
  1505.     }
  1506.  
  1507.   for (t = result; string && *string; string++)
  1508.     {
  1509.       if (*string == CTLESC)
  1510.     {
  1511.       string++;
  1512.  
  1513.       if (!*string)
  1514.         break;
  1515.     }
  1516.  
  1517.       *t++ = *string;
  1518.     }
  1519.  
  1520.   *t = '\0';
  1521.   return (result);
  1522. }
  1523.  
  1524. /* Quote the entire WORD_LIST list. */
  1525. static void
  1526. quote_list (list)
  1527.      WORD_LIST *list;
  1528. {
  1529.   register WORD_LIST *w;
  1530.  
  1531.   for (w = list; w; w = w->next)
  1532.     {
  1533.       char *t = w->word->word;
  1534.       w->word->word = quote_string (t);
  1535.       free (t);
  1536.       w->word->quoted = 1;
  1537.     }
  1538. }
  1539.  
  1540. /* **************************************************************** */
  1541. /*                                    */
  1542. /*            Functions for Removing Patterns            */
  1543. /*                                    */
  1544. /* **************************************************************** */
  1545.  
  1546. /* Remove the portion of PARAM matched by PATTERN according to OP, where OP
  1547.    can have one of 4 values:
  1548.     RP_LONG_LEFT    remove longest matching portion at start of PARAM
  1549.     RP_SHORT_LEFT    remove shortest matching portion at start of PARAM
  1550.     RP_LONG_RIGHT    remove longest matching portion at end of PARAM
  1551.     RP_SHORT_RIGHT    remove shortest matching portion at end of PARAM
  1552. */
  1553.  
  1554. #define RP_LONG_LEFT    1
  1555. #define RP_SHORT_LEFT    2
  1556. #define RP_LONG_RIGHT    3
  1557. #define RP_SHORT_RIGHT    4
  1558.  
  1559. static char *
  1560. remove_pattern (param, pattern, op)
  1561.      char *param, *pattern;
  1562.      int op;
  1563. {
  1564.   register int len = param ? strlen (param) : 0;
  1565.   register char *end = param + len;
  1566.   register char *p, *ret, c;
  1567.  
  1568.   if (pattern == NULL || *pattern == '\0')    /* minor optimization */
  1569.     return (savestring (param));
  1570.  
  1571.   if (param == NULL || *param == '\0')
  1572.     return (param);
  1573.  
  1574.   switch (op)
  1575.     {
  1576.       case RP_LONG_LEFT:    /* remove longest match at start */
  1577.     for (p = end; p >= param; p--)
  1578.       {
  1579.         c = *p; *p = '\0';
  1580.         if (fnmatch (pattern, param, 0) != FNM_NOMATCH)
  1581.           {
  1582.         *p = c;
  1583.         return (savestring (p));
  1584.           }
  1585.         *p = c;
  1586.       }
  1587.     break;
  1588.  
  1589.       case RP_SHORT_LEFT:    /* remove shortest match at start */
  1590.     for (p = param; p <= end; p++)
  1591.       {
  1592.         c = *p; *p = '\0';
  1593.         if (fnmatch (pattern, param, 0) != FNM_NOMATCH)
  1594.           {
  1595.         *p = c;
  1596.         return (savestring (p));
  1597.           }
  1598.         *p = c;
  1599.       }
  1600.     break;
  1601.  
  1602.       case RP_LONG_RIGHT:    /* remove longest match at end */
  1603.     for (p = param; p <= end; p++)
  1604.       {
  1605.         if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
  1606.           {
  1607.         c = *p;
  1608.         *p = '\0';
  1609.         ret = savestring (param);
  1610.         *p = c;
  1611.         return (ret);
  1612.           }
  1613.       }
  1614.     break;
  1615.  
  1616.       case RP_SHORT_RIGHT:    /* remove shortest match at end */
  1617.     for (p = end; p >= param; p--)
  1618.       {
  1619.         if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
  1620.           {
  1621.         c = *p;
  1622.         *p = '\0';
  1623.         ret = savestring (param);
  1624.         *p = c;
  1625.         return (ret);
  1626.           }
  1627.       }
  1628.     break;
  1629.     }
  1630.   return (savestring (param));    /* no match, return original string */
  1631. }
  1632.  
  1633. /*******************************************
  1634.  *                       *
  1635.  *    Functions to expand WORD_DESCs       *
  1636.  *                       *
  1637.  *******************************************/
  1638.  
  1639. /* Expand WORD, performing word splitting on the result.  This does
  1640.    parameter expansion, command substitution, arithmetic expansion,
  1641.    word splitting, and quote removal. */
  1642.  
  1643. WORD_LIST *
  1644. expand_word (word, quoted)
  1645.      WORD_DESC *word;
  1646.      int quoted;
  1647. {
  1648.   WORD_LIST *result, *tresult;
  1649.  
  1650.   tresult = call_expand_word_internal (word, quoted, (int *)NULL, (int *)NULL);
  1651.   result = word_list_split (tresult);
  1652.   dispose_words (tresult);
  1653.   if (result)
  1654.     dequote_list (result);
  1655.   return (result);
  1656. }
  1657.  
  1658. /* Expand WORD, but do not perform word splitting on the result.  This
  1659.    does parameter expansion, command substitution, arithmetic expansion,
  1660.    and quote removal. */
  1661. WORD_LIST *
  1662. expand_word_no_split (word, quoted)
  1663.      WORD_DESC *word;
  1664.      int quoted;
  1665. {
  1666.   WORD_LIST *result;
  1667.  
  1668.   result = call_expand_word_internal (word, quoted, (int *)NULL, (int *)NULL);
  1669.   if (result)
  1670.     dequote_list (result);
  1671.   return (result);
  1672. }
  1673.  
  1674. /* Perform shell expansions on WORD, but do not perform word splitting or
  1675.    quote removal on the result. */
  1676. WORD_LIST *
  1677. expand_word_leave_quoted (word, quoted)
  1678.      WORD_DESC *word;
  1679.      int quoted;
  1680. {
  1681.   WORD_LIST *result;
  1682.  
  1683.   result = call_expand_word_internal (word, quoted, (int *)NULL, (int *)NULL);
  1684.   return (result);
  1685. }
  1686.  
  1687. /* Return the value of a positional parameter.  This handles values > 10. */
  1688. char *
  1689. get_dollar_var_value (ind)
  1690.      int ind;
  1691. {
  1692.   char *temp;
  1693.  
  1694.   if (ind < 10)
  1695.     {
  1696.       if (dollar_vars[ind])
  1697.     temp = savestring (dollar_vars[ind]);
  1698.       else
  1699.     temp = (char *)NULL;
  1700.     }
  1701.   else    /* We want something like ${11} */
  1702.     {
  1703.       WORD_LIST *p = rest_of_args;
  1704.  
  1705.       ind -= 10;
  1706.       while (p && ind--)
  1707.     p = p->next;
  1708.       if (p)
  1709.     temp = savestring (p->word->word);
  1710.       else
  1711.     temp = (char *)NULL;
  1712.     }
  1713.   return (temp);
  1714. }
  1715.  
  1716. #if defined (PROCESS_SUBSTITUTION)
  1717.  
  1718. /* **************************************************************** */
  1719. /*                                  */
  1720. /*            Hacking Process Substitution            */
  1721. /*                                  */
  1722. /* **************************************************************** */
  1723.  
  1724. extern struct fd_bitmap *current_fds_to_close;
  1725. extern char *mktemp ();
  1726.  
  1727. #if !defined (HAVE_DEV_FD)
  1728. /* Named pipes must be removed explicitly with `unlink'.  This keeps a list
  1729.    of FIFOs the shell has open.  unlink_fifo_list will walk the list and
  1730.    unlink all of them. add_fifo_list adds the name of an open FIFO to the
  1731.    list.  NFIFO is a count of the number of FIFOs in the list. */
  1732. #define FIFO_INCR 20
  1733.  
  1734. static char **fifo_list = (char **)NULL;
  1735. static int nfifo = 0;
  1736. static int fifo_list_size = 0;
  1737.  
  1738. static void
  1739. add_fifo_list (pathname)
  1740.      char *pathname;
  1741. {
  1742.   if (nfifo >= fifo_list_size - 1)
  1743.     {
  1744.       fifo_list_size += FIFO_INCR;
  1745.       fifo_list = (char **)xrealloc (fifo_list,
  1746.                      fifo_list_size * sizeof (char *));
  1747.     }
  1748.  
  1749.   fifo_list[nfifo++] = savestring (pathname);
  1750. }
  1751.  
  1752. void
  1753. unlink_fifo_list ()
  1754. {
  1755.   if (!nfifo)
  1756.     return;
  1757.  
  1758.   while (nfifo--)
  1759.     {
  1760.       unlink (fifo_list[nfifo]);
  1761.       free (fifo_list[nfifo]);
  1762.       fifo_list[nfifo] = (char *)NULL;
  1763.     }
  1764.   nfifo = 0;
  1765. }
  1766.  
  1767. static char *
  1768. make_named_pipe ()
  1769. {
  1770.   char *tname;
  1771.  
  1772.   tname = mktemp (savestring ("/tmp/sh-np-XXXXXX"));
  1773.   if (mkfifo (tname, 0666) < 0)
  1774.     {
  1775.       free (tname);
  1776.       return ((char *)NULL);
  1777.     }
  1778.  
  1779.   add_fifo_list (tname);
  1780.   return (tname);
  1781. }
  1782.  
  1783. #if !defined (_POSIX_VERSION)
  1784. int
  1785. mkfifo (path, mode)
  1786.      char *path;
  1787.      int mode;
  1788. {
  1789. #if defined (S_IFIFO)
  1790.   return (mknod (path, (mode | S_IFIFO), 0));
  1791. #else /* !S_IFIFO */
  1792.   return (-1);
  1793. #endif /* !S_IFIFO */
  1794. }
  1795. #endif /* !_POSIX_VERSION */
  1796.  
  1797. #else /* HAVE_DEV_FD */
  1798.  
  1799. /* DEV_FD_LIST is a bitmap of file descriptors attached to pipes the shell
  1800.    has open to children.  NFDS is a count of the number of bits currently
  1801.    set in DEV_FD_LIST.  TOTFDS is a count of the highest possible number
  1802.    of open files. */
  1803. static char *dev_fd_list = (char *)NULL;
  1804. static int nfds = 0;
  1805. static int totfds;    /* The highest possible number of open files. */
  1806.  
  1807. static void
  1808. add_fifo_list (fd)
  1809.      int fd;
  1810. {
  1811.   if (!dev_fd_list || fd >= totfds)
  1812.     {
  1813.       int zero;
  1814.  
  1815.       totfds = getdtablesize ();
  1816.       if (totfds < 0 || totfds > 256)
  1817.     totfds = 256;
  1818.       if (fd > totfds)
  1819.     totfds = fd + 2;
  1820.  
  1821.       zero = dev_fd_list == (char *) NULL;
  1822.       dev_fd_list = xrealloc (dev_fd_list, totfds);
  1823.       if (zero)
  1824.     bzero (dev_fd_list, totfds);
  1825.       /* XXX - should zero out new portion of list here - XXX */
  1826.     }
  1827.  
  1828.   dev_fd_list[fd] = 1;
  1829.   nfds++;
  1830. }
  1831.  
  1832. void
  1833. unlink_fifo_list ()
  1834. {
  1835.   register int i;
  1836.  
  1837.   if (!nfds)
  1838.     return;
  1839.  
  1840.   for (i = 0; nfds && i < totfds; i++)
  1841.     if (dev_fd_list[i])
  1842.       {
  1843.     close (i);
  1844.     dev_fd_list[i] = 0;
  1845.     nfds--;
  1846.       }
  1847.  
  1848.   nfds = 0;
  1849. }
  1850.  
  1851. #if defined (NOTDEF)
  1852. print_dev_fd_list ()
  1853. {
  1854.   register int i;
  1855.  
  1856.   fprintf (stderr, "pid %d: dev_fd_list:", getpid ());
  1857.   fflush (stderr);
  1858.  
  1859.   for (i = 0; i < totfds; i++)
  1860.     {
  1861.       if (dev_fd_list[i])
  1862.     fprintf (stderr, " %d", i);
  1863.     }
  1864.   fprintf (stderr, "\n");
  1865. }
  1866. #endif /* NOTDEF */
  1867.  
  1868. static char *
  1869. make_dev_fd_filename (fd)
  1870.      int fd;
  1871. {
  1872.   char *ret;
  1873.  
  1874.   ret = xmalloc (16 * sizeof (char));
  1875.   sprintf (ret, "/dev/fd/%d", fd);
  1876.   add_fifo_list (fd);
  1877.   return (ret);
  1878. }
  1879.  
  1880. #endif /* HAVE_DEV_FD */
  1881.  
  1882. /* Return a filename that will open a connection to the process defined by
  1883.    executing STRING.  HAVE_DEV_FD, if defined, means open a pipe and return
  1884.    a filename in /dev/fd corresponding to a descriptor that is one of the
  1885.    ends of the pipe.  If not defined, we use named pipes on systems that have
  1886.    them.  Systems without /dev/fd and named pipes are out of luck.
  1887.  
  1888.    OPEN_FOR_READ_IN_CHILD, if 1, means open the named pipe for reading or
  1889.    use the read end of the pipe and dup that file descriptor to fd 0 in
  1890.    the child.  If OPEN_FOR_READ_IN_CHILD is 0, we open the named pipe for
  1891.    writing or use the write end of the pipe in the child, and dup that
  1892.    file descriptor to fd 1 in the child.  The parent does the opposite. */
  1893.  
  1894. static char *
  1895. process_substitute (string, open_for_read_in_child)
  1896.      char *string;
  1897.      int open_for_read_in_child;
  1898. {
  1899.   char *pathname;
  1900.   int fd, result;
  1901.   pid_t old_pid, pid;
  1902. #if defined (HAVE_DEV_FD)
  1903.   int parent_pipe_fd, child_pipe_fd;
  1904.   int fildes[2];
  1905. #endif /* HAVE_DEV_FD */
  1906. #if defined (JOB_CONTROL)
  1907.   pid_t old_pipeline_pgrp;
  1908. #endif  
  1909.  
  1910.   if (!string || !*string)
  1911.     return ((char *)NULL);
  1912.  
  1913. #if !defined (HAVE_DEV_FD)
  1914.   pathname = make_named_pipe ();
  1915. #else /* HAVE_DEV_FD */
  1916.   if (pipe (fildes) < 0)
  1917.     {
  1918.       internal_error ("can't make pipes for process substitution: %s",
  1919.     strerror (errno));
  1920.       return ((char *)NULL);
  1921.     }
  1922.   /* If OPEN_FOR_READ_IN_CHILD == 1, we want to use the write end of
  1923.      the pipe in the parent, otherwise the read end. */
  1924.   parent_pipe_fd = fildes[open_for_read_in_child];
  1925.   child_pipe_fd = fildes[1 - open_for_read_in_child];
  1926.   pathname = make_dev_fd_filename (parent_pipe_fd);
  1927. #endif /* HAVE_DEV_FD */
  1928.  
  1929.   if (!pathname)
  1930.     {
  1931.       internal_error ("cannot make pipe for process subsitution: %s",
  1932.     strerror (errno));
  1933.       return ((char *)NULL);
  1934.     }
  1935.  
  1936.   old_pid = last_made_pid;
  1937.  
  1938. #if defined (JOB_CONTROL)
  1939.   old_pipeline_pgrp = pipeline_pgrp;
  1940.   pipeline_pgrp = shell_pgrp;
  1941.   pid = make_child ((char *)NULL, 1);
  1942.   if (pid == 0)
  1943.     {
  1944.       /* Cancel traps, in trap.c. */
  1945.       restore_original_signals ();
  1946.       setup_async_signals ();
  1947.       subshell_environment++;
  1948.     }
  1949.   set_sigchld_handler ();
  1950.   stop_making_children ();
  1951.   pipeline_pgrp = old_pipeline_pgrp;
  1952. #else /* !JOB_CONTROL */
  1953.   pid = make_child ((char *)NULL, 1);
  1954.   if (pid == 0)
  1955.     {
  1956.       /* Cancel traps, in trap.c. */
  1957.       restore_original_signals ();
  1958.       setup_async_signals ();
  1959.       subshell_environment++;
  1960.     }
  1961. #endif /* !JOB_CONTROL */
  1962.  
  1963.   set_sigint_handler ();
  1964.  
  1965.   if (pid < 0)
  1966.     {
  1967.       internal_error ("cannot make a child for process substitution: %s",
  1968.     strerror (errno));
  1969.       free (pathname);
  1970. #if defined (HAVE_DEV_FD)
  1971.       close (parent_pipe_fd);
  1972.       close (child_pipe_fd);
  1973. #endif /* HAVE_DEV_FD */
  1974.       return ((char *)NULL);
  1975.     }
  1976.  
  1977.   if (pid > 0)
  1978.     {
  1979.       last_made_pid = old_pid;
  1980.  
  1981. #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
  1982.       close_pgrp_pipe ();
  1983. #endif /* JOB_CONTROL && PGRP_PIPE */
  1984.  
  1985. #if defined (HAVE_DEV_FD)
  1986.       close (child_pipe_fd);
  1987. #endif /* HAVE_DEV_FD */
  1988.  
  1989.       return (pathname);
  1990.     }
  1991.  
  1992. #if defined (JOB_CONTROL)
  1993.   set_job_control (0);
  1994. #endif /* JOB_CONTROL */
  1995.  
  1996. #if !defined (HAVE_DEV_FD)
  1997.   /* Open the named pipe in the child. */
  1998.   fd = open (pathname, open_for_read_in_child ? O_RDONLY : O_WRONLY);
  1999.   if (fd < 0)
  2000.     {
  2001.       internal_error ("cannot open named pipe %s for %s: %s", pathname,
  2002.     open_for_read_in_child ? "reading" : "writing", strerror (errno));
  2003.       exit (127);
  2004.     }
  2005. #else /* HAVE_DEV_FD */
  2006.   fd = child_pipe_fd;
  2007. #endif /* HAVE_DEV_FD */
  2008.  
  2009.   if (dup2 (fd, open_for_read_in_child ? 0 : 1) < 0)
  2010.     {
  2011.       internal_error ("cannot duplicate named pipe %s as fd %d: %s",
  2012.     pathname, open_for_read_in_child ? 0 : 1, strerror (errno));
  2013.       exit (127);
  2014.     }
  2015.  
  2016.   close (fd);
  2017.  
  2018.   /* Need to close any files that this process has open to pipes inherited
  2019.      from its parent. */
  2020.   if (current_fds_to_close)
  2021.     {
  2022.       close_fd_bitmap (current_fds_to_close);
  2023.       current_fds_to_close = (struct fd_bitmap *)NULL;
  2024.     }
  2025.  
  2026. #if defined (HAVE_DEV_FD)
  2027.   /* Make sure we close the parent's end of the pipe and clear the slot
  2028.      in the fd list so it is not closed later, if reallocated by, for
  2029.      instance, pipe(2). */
  2030.   close (parent_pipe_fd);
  2031.   dev_fd_list[parent_pipe_fd] = 0;
  2032. #endif /* HAVE_DEV_FD */
  2033.  
  2034.   result = parse_and_execute (string, "process substitution", 0);
  2035.  
  2036. #if !defined (HAVE_DEV_FD)
  2037.   /* Make sure we close the named pipe in the child before we exit. */
  2038.   close (open_for_read_in_child ? 0 : 1);
  2039. #endif /* !HAVE_DEV_FD */
  2040.  
  2041.   exit (result);
  2042.   /*NOTREACHED*/
  2043. }
  2044. #endif /* PROCESS_SUBSTITUTION */
  2045.  
  2046. /* Perform command substitution on STRING.  This returns a string,
  2047.    possibly quoted. */
  2048. static char *
  2049. command_substitute (string, quoted)
  2050.      char *string;
  2051.      int quoted;
  2052. {
  2053.   pid_t pid, old_pid;
  2054.   int fildes[2];
  2055.   char *istring = (char *)NULL;
  2056.   int istring_index, istring_size, c = 1;
  2057.   int result;
  2058.  
  2059.   istring_index = istring_size = 0;
  2060.  
  2061.   /* Don't fork () if there is no need to.  In the case of no command to
  2062.      run, just return NULL. */
  2063.   if (!string || !*string || (string[0] == '\n' && !string[1]))
  2064.     return ((char *)NULL);
  2065.  
  2066.   /* Pipe the output of executing STRING into the current shell. */
  2067.   if (pipe (fildes) < 0)
  2068.     {
  2069.       internal_error ("Can't make pipes for command substitution!");
  2070.       goto error_exit;
  2071.     }
  2072.  
  2073.   old_pid = last_made_pid;
  2074. #if defined (JOB_CONTROL)
  2075.   {
  2076.     pid_t old_pipeline_pgrp = pipeline_pgrp;
  2077.  
  2078.     pipeline_pgrp = shell_pgrp;
  2079.     pid = make_child ((char *)NULL, 0);
  2080.     if (pid == 0)
  2081.       /* Reset the signal handlers in the child, but don't free the
  2082.      trap strings. */
  2083.       reset_signal_handlers ();
  2084.     set_sigchld_handler ();
  2085.     stop_making_children ();
  2086.     pipeline_pgrp = old_pipeline_pgrp;
  2087.   }
  2088. #else /* !JOB_CONTROL */
  2089.   pid = make_child ((char *)NULL, 0);
  2090.  
  2091.   if (pid == 0)
  2092.     /* Reset the signal handlers in the child, but don't free the
  2093.        trap strings. */
  2094.     reset_signal_handlers ();
  2095. #endif /* !JOB_CONTROL */
  2096.  
  2097.   set_sigint_handler ();    /* XXX - move after error check? */
  2098.  
  2099.   if (pid < 0)
  2100.     {
  2101.       internal_error ("Can't make a child for command substitution: %s",
  2102.     strerror (errno));
  2103.     error_exit:
  2104.  
  2105.       FREE (istring);
  2106.       close (fildes[0]);
  2107.       close (fildes[1]);
  2108.       return ((char *)NULL);
  2109.     }
  2110.  
  2111.   if (pid == 0)
  2112.     {
  2113. #if defined (JOB_CONTROL)
  2114.       set_job_control (0);
  2115. #endif
  2116.       if (dup2 (fildes[1], 1) < 0)
  2117.     {
  2118.       internal_error
  2119.         ("command_substitute: cannot duplicate pipe as fd 1: %s",
  2120.          strerror (errno));
  2121.       exit (EXECUTION_FAILURE);
  2122.     }
  2123.  
  2124.       /* If standard output is closed in the parent shell
  2125.      (such as after `exec >&-'), file descriptor 1 will be
  2126.      the lowest available file descriptor, and end up in
  2127.      fildes[0].  This can happen for stdin and stderr as well,
  2128.      but stdout is more important -- it will cause no output
  2129.      to be generated from this command. */
  2130.       if ((fildes[1] != fileno (stdin)) &&
  2131.       (fildes[1] != fileno (stdout)) &&
  2132.       (fildes[1] != fileno (stderr)))
  2133.     close (fildes[1]);
  2134.  
  2135.       if ((fildes[0] != fileno (stdin)) &&
  2136.       (fildes[0] != fileno (stdout)) &&
  2137.       (fildes[0] != fileno (stderr)))
  2138.     close (fildes[0]);
  2139.  
  2140.       /* The currently executing shell is not interactive. */
  2141.       interactive = 0;
  2142.  
  2143.       remove_quoted_escapes (string);
  2144.  
  2145.       /* Give command substitution a place to jump back to on failure,
  2146.      so we don't go back up to main (). */
  2147.       result = setjmp (top_level);
  2148.  
  2149.       if (result == EXITPROG)
  2150.     exit (last_command_exit_value);
  2151.       else if (result)
  2152.     exit (EXECUTION_FAILURE);
  2153.       else
  2154.     exit (parse_and_execute (string, "command substitution", -1));
  2155.     }
  2156.   else
  2157.     {
  2158.       FILE *istream;
  2159.  
  2160.       istream = fdopen (fildes[0], "r");
  2161.  
  2162. #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
  2163.       close_pgrp_pipe ();
  2164. #endif /* JOB_CONTROL && PGRP_PIPE */
  2165.  
  2166.       close (fildes[1]);
  2167.  
  2168.       if (!istream)
  2169.     {
  2170.       internal_error ("Can't reopen pipe to command substitution (fd %d): %s",
  2171.             fildes[0], strerror (errno));
  2172.       goto error_exit;
  2173.     }
  2174.  
  2175.       /* Read the output of the command through the pipe. */
  2176.       while (1)
  2177.     {
  2178. #if defined (NO_READ_RESTART_ON_SIGNAL)
  2179.       c = getc_with_restart (istream);
  2180. #else
  2181.       c = getc (istream);
  2182. #endif /* !NO_READ_RESTART_ON_SIGNAL */
  2183.  
  2184.       if (c == EOF)
  2185.         break;
  2186.  
  2187.       /* Add the character to ISTRING. */
  2188.       if (istring_index + 2 >= istring_size)
  2189.         {
  2190.           while (istring_index + 2 >= istring_size)
  2191.         istring_size += DEFAULT_ARRAY_SIZE;
  2192.           istring = xrealloc (istring, istring_size);
  2193.         }
  2194.  
  2195.       if (quoted || c == CTLESC || c == CTLNUL)
  2196.         istring[istring_index++] = CTLESC;
  2197.  
  2198.       istring[istring_index++] = c;
  2199.       istring[istring_index] = '\0';
  2200.     }
  2201.  
  2202.       fclose (istream);
  2203.       close (fildes[0]);
  2204.  
  2205.       last_command_exit_value = wait_for (pid);
  2206.       last_command_subst_pid = pid;
  2207.       last_made_pid = old_pid;
  2208.  
  2209. #if defined (JOB_CONTROL)
  2210.       /* If last_command_exit_value > 128, then the substituted command
  2211.      was terminated by a signal.  If that signal was SIGINT, then send
  2212.      SIGINT to ourselves.  This will break out of loops, for instance. */
  2213.       if (last_command_exit_value == (128 + SIGINT))
  2214.     kill (getpid (), SIGINT);
  2215.  
  2216.       /* wait_for gives the terminal back to shell_pgrp.  If some other
  2217.      process group should have it, give it away to that group here. */
  2218.       if (interactive && pipeline_pgrp != (pid_t)0)
  2219.     give_terminal_to (pipeline_pgrp);
  2220. #endif /* JOB_CONTROL */
  2221.  
  2222.       /* If we read no output, just return now and save ourselves some
  2223.      trouble. */
  2224.       if (istring_index == 0)
  2225.     goto error_exit;
  2226.  
  2227.       /* Strip trailing newlines from the output of the command. */
  2228.       if (quoted)
  2229.     {
  2230.       while (istring_index > 0)
  2231.         {
  2232.           if (istring[istring_index - 1] == '\n')
  2233.         {
  2234.           --istring_index;
  2235.  
  2236.           /* If the newline was quoted, remove the quoting char. */
  2237.           if (istring[istring_index - 1] == CTLESC)
  2238.             --istring_index;
  2239.         }
  2240.           else
  2241.         break;
  2242.         }
  2243.       istring[istring_index] = '\0';
  2244.     }
  2245.       else
  2246.     strip_trailing (istring, 1);
  2247.  
  2248.       return (istring);
  2249.     }
  2250. }
  2251.  
  2252. /********************************************************
  2253.  *                            *
  2254.  *    Utility functions for parameter expansion    *
  2255.  *                            *
  2256.  ********************************************************/
  2257.  
  2258. /* Handle removing a pattern from a string as a result of ${name%[%]value}
  2259.    or ${name#[#]value}. */
  2260. static char *
  2261. parameter_brace_remove_pattern (value, temp, c)
  2262.      char *value, *temp;
  2263.      int c;
  2264. {
  2265.   int pattern_specifier;
  2266.   WORD_LIST *l;
  2267.   char *pattern, *t, *tword;
  2268.  
  2269.   if (c == '#')
  2270.     {
  2271.       if (*value == '#')
  2272.     {
  2273.       value++;
  2274.       pattern_specifier = RP_LONG_LEFT;
  2275.     }
  2276.       else
  2277.     pattern_specifier = RP_SHORT_LEFT;
  2278.     }
  2279.   else    /* c == '%' */
  2280.     {
  2281.       if (*value == '%')
  2282.     {
  2283.       value++;
  2284.       pattern_specifier = RP_LONG_RIGHT;
  2285.     }
  2286.       else
  2287.     pattern_specifier = RP_SHORT_RIGHT;
  2288.     }
  2289.  
  2290.   /* Posix.2 says that the WORD should be run through tilde expansion,
  2291.      parameter expansion, command substitution and arithmetic expansion.
  2292.      This leaves the result quoted, so quote_string_for_globbing () has
  2293.      to be called to fix it up for fnmatch (). */
  2294.   if (strchr (value, '~'))
  2295.     tword = tilde_expand (value);
  2296.   else
  2297.     tword = savestring (value);
  2298.  
  2299.   /* expand_string_internal () leaves WORD quoted and does not perform
  2300.      word splitting. */
  2301.   l = expand_string_internal (tword, 0);
  2302.   free (tword);
  2303.   pattern = string_list (l);
  2304.   dispose_words (l);
  2305.  
  2306.   if (pattern)
  2307.     {
  2308.       tword = quote_string_for_globbing (pattern, 1);
  2309.       free (pattern);
  2310.       pattern = tword;
  2311.     }
  2312.  
  2313.   t = remove_pattern (temp, pattern, pattern_specifier);
  2314.  
  2315.   FREE (pattern);
  2316.   return (t);
  2317. }
  2318.  
  2319. static int
  2320. valid_brace_expansion_word (name, var_is_special)
  2321.      char *name;
  2322.      int var_is_special;
  2323. {
  2324.   if (digit (*name) && all_digits (name))
  2325.     return 1;
  2326.   else if (var_is_special)
  2327.     return 1;
  2328.   else if (legal_identifier (name))
  2329.     return 1;
  2330.   else
  2331.     return 0;
  2332. }
  2333. /* Parameter expand NAME, and return a new string which is the expansion,
  2334.    or NULL if there was no expansion.
  2335.    VAR_IS_SPECIAL is non-zero if NAME is one of the special variables in
  2336.    the shell, e.g., "@", "$", "*", etc.  QUOTED, if non-zero, means that
  2337.    NAME was found inside of a double-quoted expression. */
  2338. static char *
  2339. parameter_brace_expand_word (name, var_is_special, quoted)
  2340.      char *name;
  2341.      int var_is_special, quoted;
  2342. {
  2343.   char *temp = (char *)NULL;
  2344.  
  2345.   /* Handle multiple digit arguments, as in ${11}. */
  2346.   if (digit (*name))
  2347.     {
  2348.       int arg_index = atoi (name);
  2349.  
  2350.       temp = get_dollar_var_value (arg_index);
  2351.     }
  2352.   else if (var_is_special)      /* ${@} */
  2353.     {
  2354.       char *tt;
  2355.       WORD_LIST *l;
  2356.  
  2357.       tt = xmalloc (2 + strlen (name));
  2358.       tt[0] = '$'; tt[1] = '\0';
  2359.       strcpy (tt + 1, name);
  2360.       l = expand_string_leave_quoted (tt, quoted);
  2361.       free (tt);
  2362.       temp = string_list (l);
  2363.       dispose_words (l);
  2364.     }
  2365.   else
  2366.     {
  2367.       SHELL_VAR *var = find_variable (name);
  2368.  
  2369.       if (var && !invisible_p (var) && (temp = value_cell (var)))
  2370.     temp = quote_escapes (temp);
  2371.     }
  2372.   return (temp);
  2373. }
  2374.  
  2375. /* Expand the right side of a parameter expansion of the form ${NAMEcVALUE},
  2376.    depending on the value of C, the separating character.  C can be one of
  2377.    "-", "+", or "=". */
  2378. static char *
  2379. parameter_brace_expand_rhs (name, value, c, quoted)
  2380.      char *name, *value;
  2381.      int c, quoted;
  2382. {
  2383.   WORD_LIST *l;
  2384.   char *t, *t1, *temp;
  2385.  
  2386.   if (value[0] == '~' ||
  2387.       (strchr (value, '~') && unquoted_substring ("=~", value)))
  2388.     temp = tilde_expand (value);
  2389.   else
  2390.     temp = savestring (value);
  2391.  
  2392.   l = expand_string_leave_quoted (temp, quoted);
  2393.   free (temp);
  2394.  
  2395.   temp = string_list (l);
  2396.   dispose_words (l);
  2397.  
  2398.   if (c == '-' || c == '+')
  2399.     return (temp);
  2400.  
  2401.   /* c == '=' */
  2402.   if (temp)
  2403.     t = savestring (temp);
  2404.   else
  2405.     t = savestring ("");
  2406.   t1 = dequote_string (t);
  2407.   free (t);
  2408.   bind_variable (name, t1);
  2409.   free (t1);
  2410.   return (temp);
  2411. }
  2412.  
  2413. /* Deal with the right hand side of a ${name:?value} expansion in the case
  2414.    that NAME is null or not set.  If VALUE is non-null it is expanded and
  2415.    used as the error message to print, otherwise a standard message is
  2416.    printed. */
  2417. static void
  2418. parameter_brace_expand_error (name, value)
  2419.      char *name, *value;
  2420. {
  2421.   if (value && *value)
  2422.     {
  2423.       WORD_LIST *l = expand_string (value, 0);
  2424.       char *temp1 =  string_list (l);
  2425.       report_error ("%s: %s", name, temp1 ? temp1 : value);
  2426.       FREE (temp1);
  2427.       dispose_words (l);
  2428.     }
  2429.   else
  2430.     report_error ("%s: parameter null or not set", name);
  2431.  
  2432.   /* Free the data we have allocated during this expansion, since we
  2433.      are about to longjmp out. */
  2434.   free (name);
  2435.   FREE (value);
  2436. }
  2437.  
  2438. /* Return 1 if NAME is something for which parameter_brace_expand_length is
  2439.    OK to do. */
  2440. static int
  2441. valid_length_expression (name)
  2442.      char *name;
  2443. {
  2444.   return (!name[1] ||                        /* ${#} */
  2445.       ((name[1] == '@' || name[1] == '*') && !name[2]) ||    /* ${#@}, ${#*} */
  2446.       (digit (name[1]) && all_digits (name + 1)) ||        /* ${#11} */
  2447.       legal_identifier (name + 1));                /* ${#PS1} */
  2448. }
  2449.  
  2450. /* Handle the parameter brace expansion that requires us to return the
  2451.    length of a parameter. */
  2452. static int
  2453. parameter_brace_expand_length (name)
  2454.      char *name;
  2455. {
  2456.   char *t;
  2457.   int number = 0;
  2458.  
  2459.   if (name[1] == '\0')            /* ${#} */
  2460.     {
  2461.       WORD_LIST *l = list_rest_of_args ();
  2462.       number = list_length (l);
  2463.       dispose_words (l);
  2464.     }
  2465.   else if (name[1] != '*' && name[1] != '@')
  2466.     {
  2467.       number = 0;
  2468.  
  2469.       if (digit (name[1]))        /* ${#1} */
  2470.     {
  2471.       if (t = get_dollar_var_value (atoi (name + 1)))
  2472.         {
  2473.           number = strlen (t);
  2474.           free (t);
  2475.         }
  2476.     }
  2477.       else                /* ${#PS1} */
  2478.     {
  2479.       WORD_LIST *list;
  2480.       char *newname;
  2481.  
  2482.       newname = savestring (name);
  2483.       newname[0] = '$';
  2484.       list = expand_string (newname, 0);
  2485.       t = string_list (list);
  2486.       free (newname);
  2487.       dispose_words (list);
  2488.  
  2489.       if (t)
  2490.         number = strlen (t);
  2491.  
  2492.       FREE (t);
  2493.     }
  2494.     }
  2495.   else                    /* ${#@} and ${#*} */
  2496.     {
  2497. #if !defined (KSH_INCOMPATIBLE)
  2498.       WORD_LIST *l = list_rest_of_args ();
  2499.       number = l ? list_length (l) : 0;
  2500.       dispose_words (l);
  2501. #else
  2502.       if (t = string_rest_of_args (1))
  2503.     {
  2504.       number = strlen (t);
  2505.       free (t);
  2506.     }
  2507. #endif /* KSH_INCOMPATIBLE */
  2508.     }
  2509.   return (number);
  2510. }
  2511.  
  2512. /* Make a word list which is the parameter and variable expansion,
  2513.    command substitution, arithmetic substitution, and quote removed
  2514.    expansion of WORD.  Return a pointer to a WORD_LIST which is the
  2515.    result of the expansion.  If WORD contains a null word, the word
  2516.    list returned is also null.
  2517.  
  2518.    QUOTED, when non-zero specifies that the text of WORD is treated
  2519.    as if it were surrounded by double quotes.
  2520.    CONTAINS_DOLLAR_AT and EXPANDED_SOMETHING are return values; when non-null
  2521.    they point to an integer value which receives information about expansion.
  2522.    CONTAINS_DOLLAR_AT gets non-zero if WORD contained "$@", else zero.
  2523.    EXPANDED_SOMETHING get non-zero if WORD contained any parameter expansions,
  2524.    else zero.
  2525.  
  2526.    This only does word splitting in the case of $@ expansion.  In that
  2527.    case, we split on ' '. */
  2528.  
  2529. /* Values for the local variable quoted_state. */
  2530. #define UNQUOTED     0
  2531. #define PARTIALLY_QUOTED 1
  2532. #define WHOLLY_QUOTED    2
  2533.  
  2534. static WORD_LIST *
  2535. expand_word_internal (word, quoted, contains_dollar_at, expanded_something)
  2536.      WORD_DESC *word;
  2537.      int quoted;
  2538.      int *contains_dollar_at;
  2539.      int *expanded_something;
  2540. {
  2541.   /* The thing that we finally output. */
  2542.   WORD_LIST *result = (WORD_LIST *)NULL;
  2543.  
  2544.   /* The intermediate string that we build while expanding. */
  2545.   char *istring = xmalloc (DEFAULT_ARRAY_SIZE);
  2546.  
  2547.   /* The current size of the above object. */
  2548.   int istring_size = DEFAULT_ARRAY_SIZE;
  2549.  
  2550.   /* Index into ISTRING. */
  2551.   int istring_index = 0;
  2552.  
  2553.   /* Temporary string storage. */
  2554.   char *temp = (char *)NULL;
  2555.  
  2556.   /* The text of WORD. */
  2557.   register char *string = word->word;
  2558.  
  2559.   /* The index into STRING. */
  2560.   int sindex = 0;
  2561.  
  2562.   /* This gets 1 if we see a $@ while quoted. */
  2563.   int quoted_dollar_at = 0;
  2564.  
  2565.   /* One of UNQUOTED, PARTIALLY_QUOTED, or WHOLLY_QUOTED, depending on
  2566.      whether WORD contains no quoting characters, a partially quoted
  2567.      string (e.g., "xx"ab), or is fully quoted (e.g., "xxab"). */
  2568.   int quoted_state = UNQUOTED;
  2569.  
  2570.   register int c;        /* Current character. */
  2571.   int number;            /* Temporary number value. */
  2572.   int t_index;            /* For calls to string_extract_xxx. */
  2573.   char *command_subst_result;    /* For calls to command_substitute (). */
  2574.  
  2575.   istring[0] = '\0';
  2576.  
  2577.   if (!string) goto final_exit;
  2578.  
  2579.   if (contains_dollar_at)
  2580.     *contains_dollar_at = 0;
  2581.  
  2582.   /* Begin the expansion. */
  2583.  
  2584.   for (;;)
  2585.     {
  2586.       c = string[sindex];
  2587.  
  2588.       /* Case on toplevel character. */
  2589.       switch (c)
  2590.     {
  2591.     case '\0':
  2592.       goto finished_with_string;
  2593.  
  2594.     case CTLESC:
  2595.       temp = xmalloc (3);
  2596.       temp[0] = CTLESC;
  2597.       temp[1] = c = string[++sindex];
  2598.       temp[2] = '\0';
  2599.  
  2600.       if (string[sindex])
  2601.         sindex++;
  2602.  
  2603.       goto add_string;
  2604.  
  2605. #if defined (PROCESS_SUBSTITUTION)
  2606.       /* Process substitution. */
  2607.     case '<':
  2608.     case '>':
  2609.       {
  2610.         char *temp1;
  2611.         int old_index;
  2612.  
  2613.         if (string[++sindex] != '(' || quoted || posixly_correct)
  2614.           {
  2615.         sindex--;
  2616.         goto add_character;
  2617.           }
  2618.         else
  2619.           old_index = ++sindex; /* skip past both '<' and '(' */
  2620.  
  2621.         temp1 = extract_process_subst
  2622.           (string, (c == '<') ? "<(" : ">(", &old_index);
  2623.         sindex = old_index;
  2624.  
  2625.         /* If the process substitution specification is `<()', we want to
  2626.            open the pipe for writing in the child and produce output; if
  2627.            it is `>()', we want to open the pipe for reading in the child
  2628.            and consume input. */
  2629.         temp = process_substitute (temp1, (c == '>'));
  2630.  
  2631.         FREE (temp1);
  2632.  
  2633.         goto dollar_add_string;
  2634.       }
  2635. #endif /* PROCESS_SUBSTITUTION */
  2636.  
  2637.     /* See about breaking this into a separate function:
  2638.         char *
  2639.         param_expand (string, sindex, quoted, expanded_something,
  2640.               contains_dollar_at, quoted_dollar_at)
  2641.         char *string;
  2642.         int *sindex, quoted, *expanded_something, *contains_dollar_at;
  2643.         int *quoted_dollar_at;
  2644.     */
  2645.     case '$':
  2646.  
  2647.       if (expanded_something)
  2648.         *expanded_something = 1;
  2649.  
  2650.       c = string[++sindex];
  2651.  
  2652.       /* Do simple cases first. Switch on what follows '$'. */
  2653.       switch (c)
  2654.         {
  2655.           /* $0 .. $9? */
  2656.         case '0':
  2657.         case '1':
  2658.         case '2':
  2659.         case '3':
  2660.         case '4':
  2661.         case '5':
  2662.         case '6':
  2663.         case '7':
  2664.         case '8':
  2665.         case '9':
  2666.           if (dollar_vars[digit_value (c)])
  2667.         temp = savestring (dollar_vars[digit_value (c)]);
  2668.           else
  2669.         temp = (char *)NULL;
  2670.           goto dollar_add_string;
  2671.  
  2672.           /* $$ -- pid of the invoking shell. */
  2673.         case '$':
  2674.           number = dollar_dollar_pid;
  2675.  
  2676.         add_number:
  2677.           temp = itos (number);
  2678.         dollar_add_string:
  2679.           if (string[sindex]) sindex++;
  2680.  
  2681.           /* Add TEMP to ISTRING. */
  2682.         add_string:
  2683.           istring = sub_append_string
  2684.         (temp, istring, &istring_index, &istring_size);
  2685.           break;
  2686.  
  2687.           /* $# -- number of positional parameters. */
  2688.         case '#':
  2689.           {
  2690.         WORD_LIST *list = list_rest_of_args ();
  2691.         number = list_length (list);
  2692.         dispose_words (list);
  2693.         goto add_number;
  2694.           }
  2695.  
  2696.           /* $? -- return value of the last synchronous command. */
  2697.         case '?':
  2698.           number = last_command_exit_value;
  2699.           goto add_number;
  2700.  
  2701.           /* $- -- flags supplied to the shell on invocation or
  2702.          by `set'. */
  2703.         case '-':
  2704.           temp = which_set_flags ();
  2705.           goto dollar_add_string;
  2706.  
  2707.           /* $! -- Pid of the last asynchronous command. */
  2708.         case '!':
  2709.           number = (int)last_asynchronous_pid;
  2710.  
  2711.           /* If no asynchronous pids have been created, echo nothing. */
  2712.           if (number == (int)NO_PID)
  2713.         {
  2714.           if (string[sindex])
  2715.             sindex++;
  2716.           if (expanded_something)
  2717.             *expanded_something = 0;
  2718.           break;
  2719.         }
  2720.           goto add_number;
  2721.  
  2722.           /* The only difference between this and $@ is when the
  2723.          arg is quoted. */
  2724.         case '*':        /* `$*' */
  2725.           temp = string_rest_of_args (quoted);
  2726.  
  2727.           /* In the case of a quoted string, quote the entire arg-list.
  2728.          "$1 $2 $3". */
  2729.           if (quoted && temp)
  2730.         {
  2731.           char *james_brown = temp;
  2732.           temp = quote_string (temp);
  2733.           free (james_brown);
  2734.         }
  2735.           goto dollar_add_string;
  2736.  
  2737.           /* When we have "$@" what we want is "$1" "$2" "$3" ... This
  2738.          means that we have to turn quoting off after we split into
  2739.          the individually quoted arguments so that the final split
  2740.          on the first character of $IFS is still done.  */
  2741.         case '@':        /* `$@' */
  2742.           {
  2743.         WORD_LIST *tlist = list_rest_of_args ();
  2744.         if (quoted && tlist)
  2745.           quote_list (tlist);
  2746.  
  2747.         /* We want to flag the fact that we saw this.  We can't turn
  2748.            off quoting entirely, because other characters in the
  2749.            string might need it (consider "\"$@\""), but we need some
  2750.            way to signal that the final split on the first character
  2751.            of $IFS should be done, even though QUOTED is 1. */
  2752.         if (quoted)
  2753.           quoted_dollar_at = 1;
  2754.         if (contains_dollar_at)
  2755.           *contains_dollar_at = 1;
  2756.         temp = string_list (tlist);
  2757.         dispose_words (tlist);        
  2758.         goto dollar_add_string;
  2759.           }
  2760.  
  2761.           /* ${[#]name[[:]#[#]%[%]-=?+[word]]} */
  2762.         case '{':
  2763.           {
  2764.         int check_nullness = 0;
  2765.         int var_is_set = 0;
  2766.         int var_is_null = 0;
  2767.         int var_is_special = 0;
  2768.         char *name, *value;
  2769.  
  2770.         t_index = ++sindex;
  2771.         name = string_extract (string, &t_index, "#%:-=?+}");
  2772.         value = (char *)NULL;
  2773.  
  2774.         /* If the name really consists of a special variable, then
  2775.            make sure that we have the entire name. */
  2776.         if (sindex == t_index &&
  2777.             (string[sindex] == '-' ||
  2778.              string[sindex] == '?' ||
  2779.              string[sindex] == '#'))
  2780.           {
  2781.             char *tt;
  2782.             t_index++;
  2783.             free (name);
  2784.             tt = string_extract (string, &t_index, "#%:-=?+}");
  2785.             name = xmalloc (2 + (strlen (tt)));
  2786.             *name = string[sindex];
  2787.             strcpy (name + 1, tt);
  2788.             free (tt);
  2789.           }
  2790.         sindex = t_index;
  2791.  
  2792.         /* Find out what character ended the variable name.  Then
  2793.            do the appropriate thing. */
  2794.         if (c = string[sindex])
  2795.           sindex++;
  2796.  
  2797.         if (c == ':')
  2798.           {
  2799.             check_nullness++;
  2800.             if (c = string[sindex])
  2801.               sindex++;
  2802.           }
  2803.  
  2804.         /* Determine the value of this variable. */
  2805.         if ((digit (*name) && all_digits (name)) ||
  2806.             (strlen (name) == 1 && member (*name, "#-?$!@*")))
  2807.           var_is_special++;
  2808.  
  2809.         /* Check for special expansion things. */
  2810.         if (*name == '#')
  2811.           {
  2812.             /* Handle ${#-} and ${#?}.  They return the lengths of
  2813.                $- and $?, respectively. */
  2814.             if (string[sindex] == '}' &&
  2815.             !name[1] &&
  2816.             !check_nullness &&
  2817.             (c == '-' || c == '?'))
  2818.               {
  2819.             char *s;
  2820.  
  2821.             free (name);
  2822.  
  2823.             if (c == '-')
  2824.               s = which_set_flags ();
  2825.             else
  2826.               s = itos (last_command_exit_value);
  2827.  
  2828.             number = STRLEN (s);
  2829.             FREE (s);
  2830.             goto add_number;
  2831.               }
  2832.  
  2833.             /* Don't allow things like ${#:-foo} to go by; they are
  2834.                errors.  If we are not pointing at the character just
  2835.                after the closing brace, then we haven't gotten all of
  2836.                the name.  Since it begins with a special character,
  2837.                this is a bad substitution.  Explicitly check for ${#:},
  2838.                which the rules do not catch. */
  2839.             if (string[sindex - 1] != '}' || member (c, "?-=+") ||
  2840.             (string[sindex - 1] == '}' && !name[1] && c == '}' &&
  2841.              check_nullness))
  2842.               {
  2843.             free (name);
  2844.             name = string;
  2845.             goto bad_substitution;
  2846.               }
  2847.  
  2848.             /* Check NAME for validity before trying to go on. */
  2849.             if (!valid_length_expression (name))
  2850.               {
  2851.             free (name);
  2852.             name = string;
  2853.             goto bad_substitution;
  2854.               }
  2855.  
  2856.             number = parameter_brace_expand_length (name);
  2857.             free (name);
  2858.             /* We are pointing one character after the brace which
  2859.                closes this expression.  Since the code at add_number
  2860.                increments SINDEX, we back up a single character. */
  2861.             sindex--;
  2862.             goto add_number;
  2863.           }
  2864.  
  2865.         /* ${@} is identical to $@. */
  2866.         if (name[0] == '@' && name[1] == '\0')
  2867.           {
  2868.             if (quoted)
  2869.               quoted_dollar_at = 1;
  2870.  
  2871.             if (contains_dollar_at)
  2872.               *contains_dollar_at = 1;
  2873.           }
  2874.  
  2875.         /* Make sure that NAME is valid before trying to go on. */
  2876.         if (!valid_brace_expansion_word (name, var_is_special))
  2877.           {
  2878.             free (name);
  2879.             name = string;
  2880.             goto bad_substitution;
  2881.           }
  2882.  
  2883.         temp =
  2884.           parameter_brace_expand_word (name, var_is_special, quoted);
  2885.  
  2886.         if (temp)
  2887.           var_is_set++;
  2888.  
  2889.         if (!var_is_set || !temp || !*temp)
  2890.           var_is_null++;
  2891.  
  2892.         if (!check_nullness)
  2893.           var_is_null = 0;
  2894.  
  2895.         /* Get the rest of the stuff inside the braces. */
  2896.         if (c && c != '}')
  2897.           {
  2898.             /* Extract the contents of the ${ ... } expansion
  2899.                according to the Posix.2 rules.  It's much less of
  2900.                a hack that the former extract_delimited_string ()
  2901.                scheme. */
  2902.             value = extract_dollar_brace_string (string, &sindex);
  2903.  
  2904.             if (string[sindex] == '}')
  2905.               sindex++;
  2906.             else
  2907.               {
  2908.             free (name);
  2909.             name = string;
  2910.             goto bad_substitution;
  2911.               }
  2912.           }
  2913.         else
  2914.           value = (char *)NULL;
  2915.  
  2916.         /* Do the right thing based on which character ended the
  2917.            variable name. */
  2918.         switch (c)
  2919.           {
  2920.           default:
  2921.             free (name);
  2922.             name = string;
  2923.             /* FALL THROUGH */
  2924.  
  2925.           case '\0':
  2926.           bad_substitution:
  2927.             report_error ("%s: bad substitution", name ? name : "??");
  2928.             FREE (value);
  2929.             free (temp);
  2930.             free (name);
  2931.             free (istring);
  2932.             return &expand_word_error;
  2933.  
  2934.           case '}':
  2935.             if (!var_is_set && unbound_vars_is_error)
  2936.               {
  2937.             report_error ("%s: unbound variable", name);
  2938.             FREE (value);
  2939.             free (temp);
  2940.             free (name);
  2941.             free (string);
  2942.             last_command_exit_value = 1;
  2943.             free (istring);
  2944.             return &expand_word_error;
  2945.               }
  2946.             break;
  2947.  
  2948.           case '#':    /* ${param#[#]pattern} */
  2949.           case '%':    /* ${param%[%]pattern} */
  2950.             {
  2951.               char *t;
  2952.               if (!value || !*value || !temp || !*temp)
  2953.             break;
  2954.               t = parameter_brace_remove_pattern (value, temp, c);
  2955.               free (temp);
  2956.               free (value);
  2957.               temp = t;
  2958.             }
  2959.             break;
  2960.  
  2961.           case '-':
  2962.           case '=':
  2963.           case '?':
  2964.           case '+':
  2965.             if (var_is_set && !var_is_null)
  2966.               {
  2967.             /* We don't want the value of the named variable for
  2968.                anything, just the value of the right hand side. */
  2969.             if (c == '+')
  2970.               {
  2971.                 FREE (temp);
  2972.                 if (value)
  2973.                   {
  2974.                 temp = parameter_brace_expand_rhs
  2975.                   (name, value, c, quoted);
  2976.                 free (value);
  2977.                   }
  2978.                 else
  2979.                   temp = (char *)NULL;
  2980.               }
  2981.             else
  2982.               {
  2983.                 FREE (value);
  2984.               }
  2985.             /* Otherwise do nothing; just use the value in TEMP. */
  2986.               }
  2987.             else    /* VAR not set or VAR is NULL. */
  2988.               {
  2989.             FREE (temp);
  2990.             temp = (char *)NULL;
  2991.             if (c == '=' && var_is_special)
  2992.               {
  2993.                 report_error
  2994.                   ("$%s: cannot assign in this way", name);
  2995.                 free (name);
  2996.                 free (value);
  2997.                 free (string);
  2998.                 free (istring);
  2999.                 return &expand_word_error;
  3000.               }
  3001.             else if (c == '?')
  3002.               {
  3003.                 free (string);
  3004.                 free (istring);
  3005.                 parameter_brace_expand_error (name, value);
  3006.                 if (!interactive)
  3007.                   return &expand_word_fatal;
  3008.                 else
  3009.                   return &expand_word_error;
  3010.               }
  3011.             else if (c != '+')
  3012.               temp = parameter_brace_expand_rhs
  3013.                 (name, value, c, 0); /* XXX was quoted, not 0 */
  3014.             free (value);
  3015.               }
  3016.             break;
  3017.           }        /* end case on closing character. */
  3018.         free (name);
  3019.         goto add_string;
  3020.           }            /* end case '{' */
  3021.           /* break; */
  3022.  
  3023.           /* Do command or arithmetic substitution. */
  3024.         case '(':
  3025.           /* We have to extract the contents of this paren substitution. */
  3026.           {
  3027.         int old_index = ++sindex;
  3028.  
  3029.         temp = extract_command_subst (string, &old_index);
  3030.         sindex = old_index;
  3031.  
  3032.         /* For Posix.2-style `$(( ))' arithmetic substitution,
  3033.            extract the expression and pass it to the evaluator. */
  3034.         if (temp && *temp == '(')
  3035.           {
  3036.             char *t = temp + 1;
  3037.             int last = strlen (t) - 1;
  3038.  
  3039.             if (t[last] != ')')
  3040.               {
  3041.             report_error ("%s: bad arithmetic substitution", temp);
  3042.             free (temp);
  3043.             free (string);
  3044.             free (istring);
  3045.             return &expand_word_error;
  3046.               }
  3047.  
  3048.             /* Cut off ending `)' */
  3049.             t[last] = '\0';
  3050.  
  3051.             /* Expand variables found inside the expression. */
  3052.             {
  3053.               WORD_LIST *l;
  3054.  
  3055.               l = expand_string (t, 1);
  3056.               t = string_list (l);
  3057.               dispose_words (l);
  3058.             }
  3059.  
  3060.             /* No error messages. */
  3061.             this_command_name = (char *)NULL;
  3062.  
  3063.             number = evalexp (t);
  3064.             free (temp);
  3065.             free (t);
  3066.  
  3067.             goto add_number;
  3068.           }
  3069.  
  3070.         goto handle_command_substitution;
  3071.           }
  3072.  
  3073.           /* Do straight arithmetic substitution. */
  3074.         case '[':
  3075.           /* We have to extract the contents of this
  3076.          arithmetic substitution. */
  3077.           {
  3078.         char *t;
  3079.         int old_index = ++sindex;
  3080.         WORD_LIST *l;
  3081.  
  3082.         temp = extract_arithmetic_subst (string, &old_index);
  3083.         sindex = old_index;
  3084.  
  3085.         /* Do initial variable expansion. */
  3086.         l = expand_string (temp, 1);
  3087.         t = string_list (l);
  3088.         dispose_words (l);
  3089.  
  3090.         /* No error messages. */
  3091.         this_command_name = (char *)NULL;
  3092.         number = evalexp (t);
  3093.         free (t);
  3094.         free (temp);
  3095.  
  3096.         goto add_number;
  3097.           }
  3098.  
  3099.         default:
  3100.           {
  3101.         /* Find the variable in VARIABLE_LIST. */
  3102.         int old_index = sindex;
  3103.         char *name;
  3104.         SHELL_VAR *var;
  3105.  
  3106.         temp = (char *)NULL;
  3107.  
  3108.         for (;
  3109.              (c = string[sindex]) &&
  3110.              (isletter (c) || digit (c) || c == '_');
  3111.              sindex++);
  3112.         name = substring (string, old_index, sindex);
  3113.  
  3114.         /* If this isn't a variable name, then just output the `$'. */
  3115.         if (!name || !*name)
  3116.           {
  3117.             FREE (name);
  3118.             temp = savestring ("$");
  3119.             if (expanded_something)
  3120.               *expanded_something = 0;
  3121.             goto add_string;
  3122.           }
  3123.  
  3124.         /* If the variable exists, return its value cell. */
  3125.         var = find_variable (name);
  3126.  
  3127.         if (var && !invisible_p (var) && value_cell (var))
  3128.           {
  3129.             temp = quote_escapes (value_cell (var));
  3130.             free (name);
  3131.             goto add_string;
  3132.           }
  3133.         else
  3134.           temp = (char *)NULL;
  3135.  
  3136.         if (unbound_vars_is_error)
  3137.           report_error ("%s: unbound variable", name);
  3138.         else
  3139.           {
  3140.             free (name);
  3141.             goto add_string;
  3142.           }
  3143.  
  3144.         free (name);
  3145.         free (string);
  3146.         last_command_exit_value = 1;
  3147.         free (istring);
  3148.         return &expand_word_error;
  3149.           }
  3150.         }
  3151.       break;        /* End case '$': */
  3152.  
  3153.     case '`':        /* Backquoted command substitution. */
  3154.       {
  3155.         sindex++;
  3156.  
  3157.         if (expanded_something)
  3158.           *expanded_something = 1;
  3159.  
  3160.         temp = string_extract (string, &sindex, "`");
  3161.         de_backslash (temp);
  3162.  
  3163.       handle_command_substitution:
  3164.         command_subst_result = command_substitute (temp, quoted);
  3165.  
  3166.         FREE (temp);
  3167.  
  3168.         temp = command_subst_result;
  3169.  
  3170.         if (string[sindex])
  3171.           sindex++;
  3172.  
  3173.         goto add_string;
  3174.       }
  3175.  
  3176.     case '\\':
  3177.       if (string[sindex + 1] == '\n')
  3178.         {
  3179.           sindex += 2;
  3180.           continue;
  3181.         }
  3182.       else
  3183.         {
  3184.           char *slashify_chars = "";
  3185.  
  3186.           c = string[++sindex];
  3187.  
  3188.           if (quoted == Q_HERE_DOCUMENT)
  3189.         slashify_chars = slashify_in_here_document;
  3190.           else if (quoted == Q_DOUBLE_QUOTES)
  3191.         slashify_chars = slashify_in_quotes;
  3192.  
  3193.           if (quoted && !member (c, slashify_chars))
  3194.         {
  3195.           temp = xmalloc (3);
  3196.           temp[0] = '\\'; temp[1] = c; temp[2] = '\0';
  3197.           if (c)
  3198.             sindex++;
  3199.           goto add_string;
  3200.         }
  3201.           else
  3202.         {
  3203.           /* This character is quoted, so add it in quoted mode. */
  3204.           temp = make_quoted_char (c);
  3205.           if (c)
  3206.             sindex++;
  3207.           goto add_string;
  3208.         }
  3209.         }
  3210.  
  3211.     case '"':
  3212.       if (quoted)
  3213.         goto add_character;
  3214.       sindex++;
  3215.       {
  3216.         WORD_LIST *tresult = (WORD_LIST *)NULL;
  3217.  
  3218.         t_index = sindex;
  3219.         temp = string_extract_double_quoted (string, &sindex);
  3220.  
  3221.         /* If the quotes surrounded the entire string, then the
  3222.            whole word was quoted. */
  3223.         if (t_index == 1 && !string[sindex])
  3224.           quoted_state = WHOLLY_QUOTED;
  3225.         else
  3226.           quoted_state = PARTIALLY_QUOTED;
  3227.  
  3228.         if (temp && *temp)
  3229.           {
  3230.         int dollar_at_flag;
  3231.         int quoting_flags = Q_DOUBLE_QUOTES;
  3232.         WORD_DESC *temp_word = make_word (temp);
  3233.  
  3234.         free (temp);
  3235.  
  3236.         tresult = expand_word_internal
  3237.           (temp_word, quoting_flags, &dollar_at_flag, (int *)NULL);
  3238.  
  3239.         if (tresult == &expand_word_error || tresult == &expand_word_fatal)
  3240.           {
  3241.             free (istring);
  3242.             free (string);
  3243.             /* expand_word_internal has already freed temp_word->word
  3244.                for us because of the way it prints error messages. */
  3245.             temp_word->word = (char *)NULL;
  3246.             dispose_word (temp_word);
  3247.             return tresult;
  3248.           }
  3249.  
  3250.         dispose_word (temp_word);
  3251.  
  3252.         /* "$@" (a double-quoted dollar-at) expands into nothing,
  3253.            not even a NULL word, when there are no positional
  3254.            parameters. */
  3255.         if (!tresult && dollar_at_flag)
  3256.           {
  3257.             quoted_dollar_at++;
  3258.             break;
  3259.           }
  3260.  
  3261.         /* If we get "$@", we know we have expanded something, so we
  3262.            need to remember it for the final split on $IFS.  This is
  3263.            a special case; it's the only case where a quoted string
  3264.            can expand into more than one word.  It's going to come back
  3265.            from the above call to expand_word_internal as a list with
  3266.            a single word, in which all characters are quoted and
  3267.            separated by blanks.  What we want to do is to turn it back
  3268.            into a list for the next piece of code. */
  3269.         dequote_list (tresult);
  3270.  
  3271.         if (dollar_at_flag)
  3272.           {
  3273.             quoted_dollar_at++;
  3274.             if (expanded_something)
  3275.               *expanded_something = 1;
  3276.           }
  3277.           }
  3278.         else
  3279.           {
  3280.         /* What we have is "".  This is a minor optimization. */
  3281.         free (temp);
  3282.         tresult = (WORD_LIST *)NULL;
  3283.           }
  3284.  
  3285.         /* The code above *might* return a list (consider the case of "$@",
  3286.            where it returns "$1", "$2", etc.).  We can't throw away the
  3287.            rest of the list, and we have to make sure each word gets added
  3288.            as quoted.  We test on tresult->next:  if it is non-NULL, we
  3289.            quote the whole list, save it to a string with string_list, and
  3290.            add that string. We don't need to quote the results of this
  3291.            (and it would be wrong, since that would quote the separators
  3292.            as well), so we go directly to add_string. */
  3293.         if (tresult)
  3294.           {
  3295.         if (tresult->next)
  3296.           {
  3297.             quote_list (tresult);
  3298.             temp = string_list (tresult);
  3299.             dispose_words (tresult);
  3300.             goto add_string;
  3301.           }
  3302.         else
  3303.           {
  3304.             temp = savestring (tresult->word->word);
  3305.             dispose_words (tresult);
  3306.           }
  3307.           }
  3308.         else
  3309.           temp = (char *)NULL;
  3310.  
  3311.         /* We do not want to add quoted nulls to strings that are only
  3312.            partially quoted; we can throw them away. */
  3313.         if (!temp && (quoted_state == PARTIALLY_QUOTED))
  3314.           continue;
  3315.  
  3316.       add_quoted_string:
  3317.  
  3318.         if (temp)
  3319.           {
  3320.         char *t = temp;
  3321.         temp = quote_string (temp);
  3322.         free (t);
  3323.           }
  3324.         else
  3325.           {
  3326.         /* Add NULL arg. */
  3327.         temp = xmalloc (2);
  3328.         temp[0] = CTLNUL;
  3329.         temp[1] = '\0';
  3330.           }
  3331.         goto add_string;
  3332.       }
  3333.       /* break; */
  3334.  
  3335.     case '\'':
  3336.       {
  3337.         if (!quoted)
  3338.           {
  3339.         sindex++;
  3340.  
  3341.         t_index = sindex;
  3342.         temp = string_extract_single_quoted (string, &sindex);
  3343.  
  3344.         /* If the entire STRING was surrounded by single quotes,
  3345.            then the string is wholly quoted. */
  3346.         if (t_index == 1 && !string[sindex])
  3347.           quoted_state = WHOLLY_QUOTED;
  3348.         else
  3349.           quoted_state = PARTIALLY_QUOTED;
  3350.  
  3351.         /* If all we had was '', it is a null expansion. */
  3352.         if (!*temp)
  3353.           {
  3354.             free (temp);
  3355.             temp = (char *)NULL;
  3356.           }
  3357.         else
  3358.           remove_quoted_escapes (temp);
  3359.  
  3360.         /* We do not want to add quoted nulls to strings that are only
  3361.            partially quoted; such nulls are discarded. */
  3362.         if (!temp && (quoted_state == PARTIALLY_QUOTED))
  3363.           continue;
  3364.  
  3365.         goto add_quoted_string;
  3366.           }
  3367.         else
  3368.           goto add_character;
  3369.  
  3370.         break;
  3371.       }
  3372.  
  3373.     default:
  3374.  
  3375.       /* This is the fix for " $@ " */
  3376.       if (quoted)
  3377.         {
  3378.           temp = make_quoted_char (c);
  3379.           if (string[sindex])
  3380.         sindex++;
  3381.           goto add_string;
  3382.         }
  3383.  
  3384.     add_character:
  3385.       if (istring_index + 1 >= istring_size)
  3386.         {
  3387.           while (istring_index + 1 >= istring_size)
  3388.         istring_size += DEFAULT_ARRAY_SIZE;
  3389.           istring = xrealloc (istring, istring_size);
  3390.         }
  3391.       istring[istring_index++] = c;
  3392.       istring[istring_index] = '\0';
  3393.  
  3394.       /* Next character. */
  3395.       sindex++;
  3396.     }
  3397.     }
  3398.  
  3399. finished_with_string:
  3400. final_exit:
  3401.   /* OK, we're ready to return.  If we have a quoted string, and
  3402.      quoted_dollar_at is not set, we do no splitting at all; otherwise
  3403.      we split on ' '.  The routines that call this will handle what to
  3404.      do if nothing has been expanded. */
  3405.   if (istring)
  3406.     {
  3407.       WORD_LIST *temp_list;
  3408.  
  3409.       /* Partially and wholly quoted strings which expand to the empty
  3410.      string are retained as an empty arguments.  Unquoted strings
  3411.      which expand to the empty string are discarded.  The single
  3412.      exception is the case of expanding "$@" when there are no
  3413.      positional parameters.  In that case, we discard the expansion. */
  3414.  
  3415.       /* Because of how the code that handles "" and '' in partially
  3416.      quoted strings works, we need to make ISTRING into a QUOTED_NULL
  3417.      if we saw quoting characters, but the expansion was empty.
  3418.      "" and '' are tossed away before we get to this point when
  3419.      processing partially quoted strings.  This makes "" and $xxx""
  3420.      equivalent when xxx is unset. */
  3421.       if (!*istring && quoted_state == PARTIALLY_QUOTED)
  3422.     {
  3423.       if (istring_size < 2)
  3424.         istring = xrealloc (istring, istring_size += 2);
  3425.       istring[0] = CTLNUL;
  3426.       istring[1] = '\0';
  3427.     }
  3428.  
  3429.       /* If we expand to nothing and there were no single or double quotes
  3430.      in the word, we throw it away.  Otherwise, we return a NULL word.
  3431.      The single exception is for $@ surrounded by double quotes when
  3432.      there are no positional parameters.  In that case, we also throw
  3433.      the word away. */
  3434.       if (!*istring)
  3435.     {
  3436.       if (quoted_state == UNQUOTED ||
  3437.           (quoted_dollar_at && quoted_state == WHOLLY_QUOTED))
  3438.         temp_list = (WORD_LIST *)NULL;
  3439.       else
  3440.         {
  3441.           temp_list = make_word_list
  3442.         (make_word (istring), (WORD_LIST *)NULL);
  3443.           temp_list->word->quoted = quoted;
  3444.         }
  3445.     }
  3446.       else
  3447.     {
  3448.       char *ifs_chars = (char *)NULL;
  3449.  
  3450.       if (quoted_dollar_at)
  3451.         {
  3452.           SHELL_VAR *ifs = find_variable ("IFS");      
  3453.           if (ifs)
  3454.         ifs_chars = value_cell (ifs);
  3455.           else
  3456.         ifs_chars = " \t\n";
  3457.         }
  3458.  
  3459.       /* According to Posix.2, "$@" expands to a single word if
  3460.          IFS="" and the positional parameters are not empty. */
  3461.       if (quoted_dollar_at && ifs_chars && *ifs_chars)
  3462.         temp_list = list_string (istring, " ", 1);
  3463.       else
  3464.         {
  3465.           temp_list = make_word_list
  3466.         (make_word (istring), (WORD_LIST *)NULL);
  3467.           temp_list->word->quoted =
  3468.         (quoted || (quoted_state == WHOLLY_QUOTED));
  3469.         }
  3470.     }
  3471.  
  3472.       free (istring);
  3473.       result = (WORD_LIST *)
  3474.     list_append (REVERSE_LIST (result, WORD_LIST *), temp_list);
  3475.     }
  3476.   else
  3477.     result = (WORD_LIST *)NULL;
  3478.  
  3479.   return (result);
  3480. }
  3481.  
  3482. /* **************************************************************** */
  3483. /*                                    */
  3484. /*           Functions for Quote Removal                */
  3485. /*                                    */
  3486. /* **************************************************************** */
  3487.  
  3488. /* Perform quote removal on STRING.  If QUOTED > 0, assume we are obeying the
  3489.    backslash quoting rules for within double quotes. */
  3490. char *
  3491. string_quote_removal (string, quoted)
  3492.      char *string;
  3493.      int quoted;
  3494. {
  3495.   char *r, *result_string, *temp, *temp1;
  3496.   int sindex, tindex, c;
  3497.  
  3498.   /* The result can be no longer than the original string. */
  3499.   r = result_string = xmalloc (strlen (string) + 1);
  3500.   sindex = 0;
  3501.  
  3502.   for (;;)
  3503.     {
  3504.       c = string[sindex];
  3505.       if (c == '\0')
  3506.     break;
  3507.  
  3508.       switch (c)
  3509.     {
  3510.       case '\\':
  3511.         c = string[++sindex];
  3512.         if (quoted && !member (c, slashify_in_quotes))
  3513.           {
  3514.         *r++ = '\\';
  3515.         *r++ = c;
  3516.           }
  3517.         else
  3518.           *r++ = c;
  3519.  
  3520.         sindex++;
  3521.         break;
  3522.  
  3523.       case '"':
  3524.         tindex = ++sindex;
  3525.         temp = string_extract_double_quoted (string, &tindex);
  3526.         sindex = tindex;
  3527.  
  3528.         temp1 = string_quote_removal (temp, 1);  /* XXX is this needed? */
  3529.  
  3530.         FREE (temp);
  3531.  
  3532.         if (temp1)
  3533.           {
  3534.         strcpy (r, temp1);
  3535.         r += strlen (r);
  3536.         free (temp1);
  3537.           }
  3538.         break;
  3539.  
  3540.       case '\'':
  3541.         if (quoted)
  3542.           {
  3543.         *r++ = c;
  3544.         sindex++;
  3545.           }
  3546.         else
  3547.           {
  3548.         tindex = ++sindex;
  3549.         temp = string_extract_single_quoted (string, &tindex);
  3550.         sindex = tindex;
  3551.  
  3552.         if (temp)
  3553.           {
  3554.             strcpy (r, temp);
  3555.             r += strlen (r);
  3556.             free (temp);
  3557.           }
  3558.           }
  3559.         break;
  3560.  
  3561.       default:
  3562.         *r++ = c;
  3563.         sindex++;
  3564.         break;
  3565.     }
  3566.     }
  3567.     *r = '\0';
  3568.     return (result_string);
  3569. }
  3570.  
  3571. /* Perform quote removal on word WORD.  This allocates and returns a new
  3572.    WORD_DESC *. */
  3573. WORD_DESC *
  3574. word_quote_removal (word, quoted)
  3575.      WORD_DESC *word;
  3576.      int quoted;
  3577. {
  3578.   WORD_DESC *w;
  3579.   char *t;
  3580.  
  3581.   t = string_quote_removal (word->word, quoted);
  3582.   w = make_word (t);
  3583.   return (w);
  3584. }
  3585.  
  3586. /* Perform quote removal on all words in LIST.  If QUOTED is non-zero,
  3587.    the members of the list are treated as if they are surrounded by
  3588.    double quotes.  Return a new list, or NULL if LIST is NULL. */
  3589. WORD_LIST *
  3590. word_list_quote_removal (list, quoted)
  3591.      WORD_LIST *list;
  3592.      int quoted;
  3593. {
  3594.   WORD_LIST *result = (WORD_LIST *)NULL, *t, *tresult;
  3595.  
  3596.   t = list;
  3597.   while (t)
  3598.     {
  3599.       tresult = (WORD_LIST *)xmalloc (sizeof (WORD_LIST));
  3600.       tresult->word = word_quote_removal (t->word, quoted);
  3601.       tresult->next = (WORD_LIST *)NULL;
  3602.       result = (WORD_LIST *) list_append (result, tresult);
  3603.       t = t->next;
  3604.     }
  3605.   return (result);
  3606. }
  3607.  
  3608. /* Return 1 if CHARACTER appears in an unquoted portion of
  3609.    STRING.  Return 0 otherwise. */
  3610. static int
  3611. unquoted_member (character, string)
  3612.      int character;
  3613.      char *string;
  3614. {
  3615.   int sindex, tindex, c;
  3616.   char *temp;
  3617.  
  3618.   sindex = 0;
  3619.  
  3620.   while (c = string[sindex])
  3621.     {
  3622.       if (c == character)
  3623.     return (1);
  3624.  
  3625.       switch (c)
  3626.     {
  3627.       case '\\':
  3628.         sindex++;
  3629.         if (string[sindex])
  3630.           sindex++;
  3631.         break;
  3632.  
  3633.       case '"':
  3634.       case '\'':
  3635.  
  3636.         tindex = ++sindex;
  3637.         if (c == '"')
  3638.           temp = string_extract_double_quoted (string, &tindex);
  3639.         else
  3640.           temp = string_extract_single_quoted (string, &tindex);
  3641.         sindex = tindex;
  3642.  
  3643.         FREE (temp);
  3644.         break;
  3645.  
  3646.       default:
  3647.         sindex++;
  3648.         break;
  3649.     }
  3650.     }
  3651.   return (0);
  3652. }
  3653.  
  3654. /* Return 1 if SUBSTR appears in an unquoted portion of STRING. */
  3655. static int
  3656. unquoted_substring (substr, string)
  3657.      char *substr, *string;
  3658. {
  3659.   int sindex, tindex, c, sublen;
  3660.   char *temp;
  3661.  
  3662.   if (!substr || !*substr)
  3663.     return (0);
  3664.  
  3665.   sublen = strlen (substr);
  3666.   sindex = 0;
  3667.  
  3668.   while (c = string[sindex])
  3669.     {
  3670.       if (STREQN (string + sindex, substr, sublen))
  3671.     return (1);
  3672.  
  3673.       switch (c)
  3674.     {
  3675.       case '\\':
  3676.         sindex++;
  3677.  
  3678.         if (string[sindex])
  3679.           sindex++;
  3680.         break;
  3681.  
  3682.       case '"':
  3683.       case '\'':
  3684.  
  3685.         tindex = ++sindex;
  3686.  
  3687.         if (c == '"')
  3688.           temp = string_extract_double_quoted (string, &tindex);
  3689.         else
  3690.           temp = string_extract_single_quoted (string, &tindex);
  3691.         sindex = tindex;
  3692.  
  3693.         FREE (temp);
  3694.  
  3695.         break;
  3696.  
  3697.       default:
  3698.         sindex++;
  3699.         break;
  3700.     }
  3701.     }
  3702.   return (0);
  3703. }
  3704.  
  3705. /*******************************************
  3706.  *                       *
  3707.  *    Functions to perform word splitting  *
  3708.  *                       *
  3709.  *******************************************/
  3710.  
  3711. /* This splits a single word into a WORD LIST on $IFS, but only if the word
  3712.    is not quoted.  list_string () performs quote removal for us, even if we
  3713.    don't do any splitting. */
  3714. WORD_LIST *
  3715. word_split (w)
  3716.      WORD_DESC *w;
  3717. {
  3718.   WORD_LIST *result;
  3719.  
  3720.   if (w)
  3721.     {
  3722.       SHELL_VAR *ifs = find_variable ("IFS");
  3723.       char *ifs_chars;
  3724.  
  3725.       /* If IFS is unset, it defaults to " \t\n". */
  3726.       if (ifs)
  3727.     ifs_chars = value_cell (ifs);
  3728.       else
  3729.     ifs_chars = " \t\n";
  3730.  
  3731.       if (w->quoted || !ifs_chars)
  3732.     ifs_chars = "";
  3733.  
  3734. #ifdef NOT_YET_MAYBE_LATER
  3735.       if (!*ifs)
  3736.     {
  3737.       /* No splitting done if word quoted or ifs set to "". */
  3738.       WORD_DESC *wtemp;
  3739.       wtemp = make_word (w->word);
  3740.       wtemp->quoted = w->quoted;
  3741.       result = make_word_list (wtemp);
  3742.     }
  3743.       else
  3744. #endif
  3745.       result = list_string (w->word, ifs_chars, w->quoted);
  3746.     }
  3747.   else
  3748.     result = (WORD_LIST *)NULL;
  3749.   return (result);
  3750. }
  3751.  
  3752. /* Perform word splitting on LIST and return the RESULT.  It is possible
  3753.    to return (WORD_LIST *)NULL. */
  3754. static WORD_LIST *
  3755. word_list_split (list)
  3756.      WORD_LIST *list;
  3757. {
  3758.   WORD_LIST *result = (WORD_LIST *)NULL, *t, *tresult;
  3759.  
  3760.   t = list;
  3761.   while (t)
  3762.     {
  3763.       tresult = word_split (t->word);
  3764.       result = (WORD_LIST *) list_append (result, tresult);
  3765.       t = t->next;
  3766.     }
  3767.   return (result);
  3768. }
  3769.  
  3770. /**************************************************
  3771.  *                           *
  3772.  *    Functions to expand an entire WORD_LIST      *
  3773.  *                          *
  3774.  **************************************************/
  3775.  
  3776. static WORD_LIST *varlist = (WORD_LIST *)NULL;
  3777.  
  3778. /* Separate out any initial variable assignments from TLIST.  If set -k has
  3779.    been executed, remove all assignment statements from TLIST.  Initial
  3780.    variable assignments and other environment assignments are placed
  3781.    on VARLIST. */
  3782. static WORD_LIST *
  3783. separate_out_assignments (tlist)
  3784.      WORD_LIST *tlist;
  3785. {
  3786.   register WORD_LIST *vp, *lp;
  3787.  
  3788.   if (!tlist)
  3789.     return ((WORD_LIST *)NULL);
  3790.  
  3791.   varlist = (WORD_LIST *)NULL;
  3792.   vp = lp = tlist;
  3793.  
  3794.   /* Separate out variable assignments at the start of the command.
  3795.      Loop invariant: vp->next == lp
  3796.      Loop postcondition:
  3797.          lp = list of words left after assignment statements skipped
  3798.          tlist = original list of words
  3799.   */
  3800.   while (lp && lp->word->assignment)
  3801.     {
  3802.       vp = lp;
  3803.       lp = lp->next;
  3804.     }
  3805.  
  3806.   /* If lp != tlist, we have some initial assignment statements. */
  3807.   /* We make VARLIST point to the list of assignment words and
  3808.      TLIST point to the remaining words.  */
  3809.   if (lp != tlist)
  3810.     {
  3811.       varlist = tlist;
  3812.       /* ASSERT(vp->next == lp); */
  3813.       vp->next = (WORD_LIST *)NULL;    /* terminate variable list */
  3814.       tlist = lp;            /* remainder of word list */
  3815.     }
  3816.  
  3817.   /* vp == end of variable list */
  3818.   /* tlist == remainder of original word list without variable assignments */
  3819.   if (!tlist)
  3820.     /* All the words in tlist were assignment statements */
  3821.     return ((WORD_LIST *)NULL);
  3822.  
  3823.   /* ASSERT(tlist != NULL); */
  3824.   /* ASSERT(tlist->word->assignment == 0); */
  3825.  
  3826.   /* If the -k option is in effect, we need to go through the remaining
  3827.      words, separate out the assignment words, and place them on VARLIST. */
  3828.   if (place_keywords_in_env)
  3829.     {
  3830.       WORD_LIST *tp;    /* tp == running pointer into tlist */
  3831.  
  3832.       tp = tlist;
  3833.       lp = tlist->next;
  3834.  
  3835.       /* Loop Invariant: tp->next == lp */
  3836.       /* Loop postcondition: tlist == word list without assignment statements */
  3837.       while (lp)
  3838.     {
  3839.       if (lp->word->assignment)
  3840.         {
  3841.           /* Found an assignment statement, add this word to end of
  3842.          varlist (vp). */
  3843.           if (!varlist)
  3844.         varlist = vp = lp;
  3845.           else
  3846.         {
  3847.           vp->next = lp;
  3848.           vp = lp;
  3849.         }
  3850.  
  3851.           /* Remove the word pointed to by LP from TLIST. */
  3852.           tp->next = lp->next;
  3853.           /* ASSERT(vp == lp); */
  3854.           lp->next = (WORD_LIST *)NULL;
  3855.           lp = tp->next;
  3856.         }
  3857.       else
  3858.         {
  3859.           tp = lp;
  3860.           lp = lp->next;
  3861.         }
  3862.     }
  3863.     }
  3864.   return (tlist);
  3865. }
  3866.  
  3867. /* Take the list of words in LIST and do the various substitutions.  Return
  3868.    a new list of words which is the expanded list, and without things like
  3869.    variable assignments. */
  3870.  
  3871. WORD_LIST *
  3872. expand_words (list)
  3873.      WORD_LIST *list;
  3874. {
  3875.   return (expand_words_internal (list, 1));
  3876. }
  3877.  
  3878. /* Same as expand_words (), but doesn't hack variable or environment
  3879.    variables. */
  3880. WORD_LIST *
  3881. expand_words_no_vars (list)
  3882.      WORD_LIST *list;
  3883. {
  3884.   return (expand_words_internal (list, 0));
  3885. }
  3886.  
  3887. /* Non-zero means to allow unmatched globbed filenames to expand to
  3888.    a null file. */
  3889. static int allow_null_glob_expansion = 0;
  3890.  
  3891. /* The workhorse for expand_words () and expand_words_no_var ().
  3892.    First arg is LIST, a WORD_LIST of words.
  3893.    Second arg DO_VARS is non-zero if you want to do environment and
  3894.    variable assignments, else zero.
  3895.  
  3896.    This does all of the substitutions: brace expansion, tilde expansion,
  3897.    parameter expansion, command substitution, arithmetic expansion,
  3898.    process substitution, word splitting, and pathname expansion. */
  3899. static WORD_LIST *
  3900. expand_words_internal (list, do_vars)
  3901.      WORD_LIST *list;
  3902.      int do_vars;
  3903. {
  3904.   register WORD_LIST *tlist, *new_list = (WORD_LIST *)NULL;
  3905.   WORD_LIST *orig_list;
  3906.  
  3907.   if (!list)
  3908.     return ((WORD_LIST *)NULL);
  3909.  
  3910.   tlist = copy_word_list (list);
  3911.  
  3912.   if (do_vars)
  3913.     {
  3914.       tlist = separate_out_assignments (tlist);
  3915.       if (!tlist)
  3916.     {
  3917.       if (varlist)
  3918.         {
  3919.           /* All the words were variable assignments, so they are placed
  3920.          into the shell's environment. */
  3921.           register WORD_LIST *lp;
  3922.           for (lp = varlist; lp; lp = lp->next)
  3923.         do_assignment (lp->word->word);
  3924.           dispose_words (varlist);
  3925.           varlist = (WORD_LIST *)NULL;
  3926.         }
  3927.       return ((WORD_LIST *)NULL);
  3928.     }
  3929.     }
  3930.  
  3931.   /* Begin expanding the words that remain.  The expansions take place on
  3932.      things that aren't really variable assignments. */
  3933.  
  3934. #if defined (BRACE_EXPANSION)
  3935.   /* Do brace expansion on this word if there are any brace characters
  3936.      in the string. */
  3937.   if (!no_brace_expansion)
  3938.     {
  3939.       register char **expansions;
  3940.       WORD_LIST *braces = (WORD_LIST *)NULL, *disposables = (WORD_LIST *)NULL;
  3941.       int eindex;
  3942.  
  3943.       while (tlist)
  3944.     {
  3945.       WORD_LIST *next;
  3946.  
  3947.       next = tlist->next;
  3948.  
  3949.       /* Only do brace expansion if the word has a brace character.  If
  3950.          not, just add the word list element to BRACES and continue.  In
  3951.          the common case, at least when running shell scripts, this will
  3952.          degenerate to a bunch of calls to `strchr', and then what is
  3953.          basically a reversal of TLIST into BRACES, which is corrected
  3954.          by a call to reverse_list () on BRACES when the end of TLIST
  3955.          is reached. */
  3956.       if (strchr (tlist->word->word, '{'))
  3957.         {
  3958.           expansions = brace_expand (tlist->word->word);
  3959.  
  3960.           for (eindex = 0; expansions[eindex]; eindex++)
  3961.         {
  3962.           braces = make_word_list (make_word (expansions[eindex]),
  3963.                          braces);
  3964.           free (expansions[eindex]);
  3965.         }
  3966.           free (expansions);
  3967.  
  3968.           /* Add TLIST to the list of words to be freed after brace
  3969.          expansion has been performed. */
  3970.           tlist->next = disposables;
  3971.           disposables = tlist;
  3972.         }
  3973.       else
  3974.         {
  3975.           tlist->next = braces;
  3976.           braces = tlist;
  3977.         }
  3978.  
  3979.       tlist = next;
  3980.     }
  3981.  
  3982.       dispose_words (disposables);
  3983.       tlist = REVERSE_LIST (braces, WORD_LIST *);
  3984.     }
  3985. #endif /* BRACE_EXPANSION */
  3986.  
  3987.   orig_list = tlist;
  3988.  
  3989.   /* We do tilde expansion all the time.  This is what 1003.2 says. */
  3990.   while (tlist)
  3991.     {
  3992.       register char *current_word;
  3993.       WORD_LIST *expanded, *t, *reversed, *next;
  3994.       int expanded_something = 0;
  3995.  
  3996.       current_word = tlist->word->word;
  3997.  
  3998.       next = tlist->next;
  3999.  
  4000.       /* Posix.2 section 3.6.1 says that tildes following `=' in words
  4001.      which are not assignment statements are not expanded.  We do
  4002.      this only if POSIXLY_CORRECT is enabled. */
  4003.       if (current_word[0] == '~' ||
  4004.       (!posixly_correct && strchr (current_word, '~') &&
  4005.        unquoted_substring ("=~", current_word)))
  4006.     {
  4007.       char *tt;
  4008.  
  4009.       tt = tlist->word->word;
  4010.       tlist->word->word = tilde_expand (tt);
  4011.       free (tt);
  4012.     }
  4013.  
  4014.       expanded = expand_word_internal
  4015.     (tlist->word, 0, (int *)NULL, &expanded_something);
  4016.  
  4017.       if (expanded == &expand_word_error || expanded == &expand_word_fatal)
  4018.     {
  4019.       /* By convention, each time this error is returned,
  4020.          tlist->word->word has already been freed. */
  4021.       tlist->word->word = (char *)NULL;
  4022.       
  4023.       /* Dispose our copy of the original list. */
  4024.       dispose_words (orig_list);
  4025.       /* Dispose the  new list we're building. */
  4026.       dispose_words (new_list);
  4027.  
  4028.       if (expanded == &expand_word_error)
  4029.         longjmp (top_level, DISCARD);
  4030.       else
  4031.         longjmp (top_level, FORCE_EOF);
  4032.     }
  4033.  
  4034.       if (expanded_something)
  4035.     {
  4036.       t = word_list_split (expanded);
  4037.       dispose_words (expanded);
  4038.     }
  4039.       else
  4040.     {
  4041.       /* If no parameter expansion, command substitution, process
  4042.          substitution, or arithmetic substitution took place, then
  4043.          do not do word splitting.  We still have to remove quoted
  4044.          null characters from the result. */
  4045.       word_list_remove_quoted_nulls (expanded);
  4046.       t = expanded;
  4047.     }
  4048.  
  4049.       /* In the most common cases, t will be a list containing only one
  4050.      element, so the call to reverse_list would be wasted. */
  4051.       reversed = REVERSE_LIST (t, WORD_LIST *);
  4052.       new_list = (WORD_LIST *)list_append (reversed, new_list);
  4053.  
  4054.       tlist = next;
  4055.     }
  4056.  
  4057.   new_list = REVERSE_LIST (new_list, WORD_LIST *);
  4058.  
  4059.   dispose_words (orig_list);
  4060.  
  4061. #if defined (USE_POSIX_GLOB_LIBRARY)
  4062. #  define GLOB_FAILED(glist)    !(glist)
  4063. #else /* !USE_POSIX_GLOB_LIBRARY */
  4064. #  define GLOB_FAILED(glist)    (glist) == (char **)&glob_error_return
  4065. #endif /* !USE_POSIX_GLOB_LIBRARY */
  4066.  
  4067.   /* Okay, we're almost done.  Now let's just do some filename
  4068.      globbing. */
  4069.   if (new_list)
  4070.     {
  4071.       char **temp_list = (char **)NULL;
  4072.       register int list_index;
  4073.       WORD_LIST *glob_list, *disposables;
  4074.  
  4075.       orig_list = disposables = (WORD_LIST *)NULL;
  4076.       tlist = new_list;
  4077.  
  4078.       /* orig_list == output list, despite the name. */
  4079.       if (!disallow_filename_globbing)
  4080.     {
  4081.       while (tlist)
  4082.         {
  4083.           /* For each word, either globbing is attempted or the word is
  4084.          added to orig_list.  If globbing succeeds, the results are
  4085.          added to orig_list and the word (tlist) is added to the list
  4086.          of disposable words.  If globbing fails and failed glob
  4087.          expansions are left unchanged (the shell default), the
  4088.          original word is added to orig_list.  If globbing fails and
  4089.          failed glob expansions are removed, the original word is
  4090.          added to the list of disposable words.  orig_list ends up
  4091.          in reverse order and requires a call to reverse_list to
  4092.          be set right.  After all words are examined, the disposable
  4093.          words are freed. */
  4094.           WORD_LIST *next;
  4095.  
  4096.           next = tlist->next;
  4097.  
  4098.           /* If the word isn't quoted and there is an unquoted pattern
  4099.          matching character in the word, then glob it. */
  4100.           if (!tlist->word->quoted &&
  4101.           unquoted_glob_pattern_p (tlist->word->word))
  4102.         {
  4103.           temp_list = shell_glob_filename (tlist->word->word);
  4104.  
  4105.           /* Handle error cases.
  4106.              I don't think we should report errors like "No such file
  4107.              or directory".  However, I would like to report errors
  4108.              like "Read failed". */
  4109.  
  4110.           if (GLOB_FAILED (temp_list))
  4111.             {
  4112.               temp_list = (char **) xmalloc (sizeof (char *));
  4113.               temp_list[0] = (char *)NULL;
  4114.             }
  4115.  
  4116.           /* Dequote the current word in case we have to use it. */
  4117.           if (!temp_list[0])
  4118.             {
  4119.               register char *t = dequote_string (tlist->word->word);
  4120.               free (tlist->word->word);
  4121.               tlist->word->word = t;
  4122.             }
  4123.  
  4124.           /* Make the array into a word list. */
  4125.           glob_list = (WORD_LIST *)NULL;
  4126.           for (list_index = 0; temp_list[list_index]; list_index++)
  4127.             glob_list = make_word_list
  4128.               (make_word (temp_list[list_index]), glob_list);
  4129.  
  4130.           if (glob_list)
  4131.             {
  4132.               orig_list = (WORD_LIST *)list_append
  4133.             (glob_list, orig_list);
  4134.               tlist->next = disposables;
  4135.               disposables = tlist;
  4136.             }
  4137.           else
  4138.             if (!allow_null_glob_expansion)
  4139.               {
  4140.             /* Failed glob expressions are left unchanged. */
  4141.             tlist->next = orig_list;
  4142.             orig_list = tlist;
  4143.               }
  4144.             else
  4145.               {
  4146.             /* Failed glob expressions are removed. */
  4147.             tlist->next = disposables;
  4148.             disposables = tlist;
  4149.               }
  4150.         }
  4151.           else
  4152.         {
  4153.           /* Dequote the string. */
  4154.           register char *t = dequote_string (tlist->word->word);
  4155.           free (tlist->word->word);
  4156.           tlist->word->word = t;
  4157.           tlist->next = orig_list;
  4158.           orig_list = tlist;
  4159.         }
  4160.  
  4161.           free_array (temp_list);
  4162.           temp_list = (char **)NULL;
  4163.  
  4164.           tlist = next;
  4165.         }
  4166.  
  4167.       if (disposables)
  4168.         dispose_words (disposables);
  4169.  
  4170.       new_list = REVERSE_LIST (orig_list, WORD_LIST *);
  4171.     }
  4172.       else
  4173.     {
  4174.       /* Dequote the words, because we're not performing globbing. */
  4175.       register WORD_LIST *wl = new_list;
  4176.       register char *wp;
  4177.       while (wl)
  4178.         {
  4179.           wp = dequote_string (wl->word->word);
  4180.           free (wl->word->word);
  4181.           wl->word->word = wp;
  4182.           wl = wl->next;
  4183.         }
  4184.     }
  4185.     }
  4186.  
  4187.   if (do_vars)
  4188.     {
  4189.       register WORD_LIST *lp;
  4190.       Function *assign_func;
  4191.  
  4192.       /* If the remainder of the words expand to nothing, Posix.2 requires
  4193.      that the variable and environment assignments affect the shell's
  4194.      environment. */
  4195.       assign_func = new_list ? assign_in_env : do_assignment;
  4196.  
  4197.       for (lp = varlist; lp; lp = lp->next)
  4198.     (*assign_func) (lp->word->word);
  4199.  
  4200.       dispose_words (varlist);
  4201.       varlist = (WORD_LIST *)NULL;
  4202.     }
  4203.  
  4204.   return (new_list);
  4205. }
  4206.  
  4207. /* Return nonzero if S has any unquoted special globbing chars in it.  */
  4208. static int
  4209. unquoted_glob_pattern_p (string)
  4210.      register char *string;
  4211. {
  4212.   register int c;
  4213.   int open = 0;
  4214.  
  4215.   while (c = *string++)
  4216.     {
  4217.       switch (c)
  4218.     {
  4219.     case '?':
  4220.     case '*':
  4221.       return (1);
  4222.  
  4223.     case '[':
  4224.       open++;
  4225.       continue;
  4226.  
  4227.     case ']':
  4228.       if (open)
  4229.         return (1);
  4230.       continue;
  4231.  
  4232.     case CTLESC:
  4233.     case '\\':
  4234.       if (*string++ == '\0')
  4235.         return (0);
  4236.     }
  4237.     }
  4238.   return (0);
  4239. }
  4240.  
  4241. /* PATHNAME can contain characters prefixed by CTLESC; this indicates
  4242.    that the character is to be quoted.  We quote it here in the style
  4243.    that the glob library recognizes.  If CONVERT_QUOTED_NULLS is non-zero,
  4244.    we change quoted null strings (pathname[0] == CTLNUL) into empty
  4245.    strings (pathname[0] == 0).  If this is called after quote removal
  4246.    is performed, CONVERT_QUOTED_NULLS should be 0; if called when quote
  4247.    removal has not been done (for example, before attempting to match a
  4248.    pattern while executing a case statement), CONVERT_QUOTED_NULLS should
  4249.    be 1. */
  4250. char *
  4251. quote_string_for_globbing (pathname, convert_quoted_nulls)
  4252.      char *pathname;
  4253.      int convert_quoted_nulls;
  4254. {
  4255.   char *temp;
  4256.   register int i;
  4257.  
  4258.   temp = savestring (pathname);
  4259.  
  4260.   if (convert_quoted_nulls && QUOTED_NULL (pathname))
  4261.     {
  4262.       temp[0] = '\0';
  4263.       return temp;
  4264.     }
  4265.  
  4266.   for (i = 0; temp[i]; i++)
  4267.     {
  4268.       if (temp[i] == CTLESC)
  4269.     temp[i++] = '\\';
  4270.     }
  4271.  
  4272.   return (temp);
  4273. }
  4274.  
  4275. /* Call the glob library to do globbing on PATHNAME. */
  4276. char **
  4277. shell_glob_filename (pathname)
  4278.      char *pathname;
  4279. {
  4280. #if defined (USE_POSIX_GLOB_LIBRARY)
  4281.   extern int glob_dot_filenames;
  4282.   register int i;
  4283.   char *temp, **return_value;
  4284.   glob_t filenames;
  4285.   int glob_flags;
  4286.  
  4287.   temp = quote_string_for_globbing (pathname, 0);
  4288.  
  4289.   filenames.gl_offs = 0;
  4290.  
  4291.   glob_flags = glob_dot_filenames ? GLOB_PERIOD : 0;
  4292.   glob_flags |= (GLOB_ERR | GLOB_DOOFFS);
  4293.  
  4294.   i = glob (temp, glob_flags, (Function *)NULL, &filenames);
  4295.  
  4296.   free (temp);
  4297.  
  4298.   if (i == GLOB_NOSPACE || i == GLOB_ABEND)
  4299.     return ((char **)NULL);
  4300.  
  4301.   if (i == GLOB_NOMATCH)
  4302.     filenames.gl_pathv[0] = (char *)NULL;
  4303.  
  4304.   return (filenames.gl_pathv);
  4305.  
  4306. #else /* !USE_POSIX_GLOB_LIBRARY */
  4307.  
  4308.   char *temp, **results;
  4309.  
  4310.   noglob_dot_filenames = !glob_dot_filenames;
  4311.  
  4312.   temp = quote_string_for_globbing (pathname, 0);
  4313.  
  4314.   results = glob_filename (temp);
  4315.   free (temp);
  4316.  
  4317.   if (results && !(GLOB_FAILED(results)))
  4318.     sort_char_array (results);
  4319.  
  4320.   return (results);
  4321. #endif /* !USE_POSIX_GLOB_LIBRARY */
  4322. }
  4323.  
  4324. /*************************************************
  4325.  *                         *
  4326.  *    Functions to manage special variables     *
  4327.  *                         *
  4328.  *************************************************/
  4329.  
  4330. /* An alist of name.function for each special variable.  Most of the
  4331.    functions don't do much, and in fact, this would be faster with a
  4332.    switch statement, but by the end of this file, I am sick of switch
  4333.    statements. */
  4334.  
  4335. /* The functions that get called. */
  4336. void
  4337.   sv_path (), sv_mail (), sv_uids (), sv_ignoreeof (),
  4338.   sv_glob_dot_filenames (), sv_nolinks (),
  4339.   sv_noclobber (), sv_allow_null_glob_expansion (), sv_strict_posix ();
  4340.  
  4341. #if defined (READLINE)
  4342. void sv_terminal (), sv_hostname_completion_file ();
  4343. #endif
  4344.  
  4345. #if defined (HISTORY)
  4346. void sv_histsize (), sv_histfilesize (), sv_histchars (),
  4347.      sv_history_control (), sv_command_oriented_history ();
  4348. #endif /* HISTORY */
  4349.  
  4350. #if defined (GETOPTS_BUILTIN)
  4351. void sv_optind (), sv_opterr ();
  4352. #endif /* GETOPTS_BUILTIN */
  4353.  
  4354. #if defined (JOB_CONTROL)
  4355. void sv_notify ();
  4356. #endif
  4357.  
  4358. #define SET_INT_VAR(name, intvar)  intvar = find_variable (name) != 0
  4359.  
  4360. struct name_and_function {
  4361.   char *name;
  4362.   VFunction *function;
  4363. } special_vars[] = {
  4364.   { "PATH", sv_path },
  4365.   { "MAIL", sv_mail },
  4366.   { "MAILPATH", sv_mail },
  4367.   { "MAILCHECK", sv_mail },
  4368.  
  4369.   { "POSIXLY_CORRECT", sv_strict_posix },
  4370.   { "POSIX_PEDANTIC", sv_strict_posix },
  4371.   /* Variables which only do something special when READLINE is defined. */
  4372. #if defined (READLINE)
  4373.   { "TERM", sv_terminal },
  4374.   { "TERMCAP", sv_terminal },
  4375.   { "TERMINFO", sv_terminal },
  4376.   { "hostname_completion_file", sv_hostname_completion_file },
  4377.   { "HOSTFILE", sv_hostname_completion_file },
  4378. #endif /* READLINE */
  4379.  
  4380.   /* Variables which only do something special when HISTORY is defined. */
  4381. #if defined (HISTORY)
  4382.   { "HISTSIZE", sv_histsize },
  4383.   { "HISTFILESIZE", sv_histfilesize },
  4384.   { "command_oriented_history", sv_command_oriented_history },
  4385.   { "histchars", sv_histchars },
  4386.   { "history_control", sv_history_control },
  4387.   { "HISTCONTROL", sv_history_control },
  4388. #endif /* HISTORY */
  4389.  
  4390.   { "EUID", sv_uids},
  4391.   { "UID", sv_uids},
  4392.   { "IGNOREEOF", sv_ignoreeof },
  4393.   { "ignoreeof", sv_ignoreeof },
  4394.  
  4395. #if defined (GETOPTS_BUILTIN)
  4396.   { "OPTIND", sv_optind },
  4397.   { "OPTERR", sv_opterr },
  4398. #endif /* GETOPTS_BUILTIN */
  4399.  
  4400. #if defined (JOB_CONTROL)
  4401.   { "notify", sv_notify },
  4402. #endif  /* JOB_CONTROL */
  4403.  
  4404.   { "glob_dot_filenames", sv_glob_dot_filenames },
  4405.   { "allow_null_glob_expansion", sv_allow_null_glob_expansion },
  4406.   { "noclobber", sv_noclobber },
  4407.   { "nolinks", sv_nolinks },
  4408.   { (char *)0x00, (VFunction *)0x00 }
  4409. };
  4410.  
  4411. /* The variable in NAME has just had its state changed.  Check to see if it
  4412.    is one of the special ones where something special happens. */
  4413. void
  4414. stupidly_hack_special_variables (name)
  4415.      char *name;
  4416. {
  4417.   int i = 0;
  4418.  
  4419.   while (special_vars[i].name)
  4420.     {
  4421.       if (STREQ (special_vars[i].name, name))
  4422.     {
  4423.       (*(special_vars[i].function)) (name);
  4424.       return;
  4425.     }
  4426.       i++;
  4427.     }
  4428. }
  4429.  
  4430. /* Set/unset noclobber. */
  4431. void
  4432. sv_noclobber (name)
  4433.      char *name;
  4434. {
  4435.   SET_INT_VAR (name, noclobber);
  4436. }
  4437.  
  4438. /* What to do just after the PATH variable has changed. */
  4439. void
  4440. sv_path (name)
  4441.      char *name;
  4442. {
  4443.   /* hash -r */
  4444.   WORD_LIST *args;
  4445.  
  4446.   args = make_word_list (make_word ("-r"), NULL);
  4447.   hash_builtin (args);
  4448.   dispose_words (args);
  4449. }
  4450.  
  4451. /* What to do just after one of the MAILxxxx variables has changed.  NAME
  4452.    is the name of the variable.  This is called with NAME set to one of
  4453.    MAIL, MAILCHECK, or MAILPATH.  */
  4454. void
  4455. sv_mail (name)
  4456.      char *name;
  4457. {
  4458.   /* If the time interval for checking the files has changed, then
  4459.      reset the mail timer.  Otherwise, one of the pathname vars
  4460.      to the users mailbox has changed, so rebuild the array of
  4461.      filenames. */
  4462.   if (name[4] == 'C')  /* if (strcmp (name, "MAILCHECK") == 0) */
  4463.     reset_mail_timer ();
  4464.   else
  4465.     {
  4466.       free_mail_files ();
  4467.       remember_mail_dates ();
  4468.     }
  4469. }
  4470.  
  4471. #if defined (READLINE)
  4472. /* What to do just after one of the TERMxxx variables has changed.
  4473.    If we are an interactive shell, then try to reset the terminal
  4474.    information in readline. */
  4475. void
  4476. sv_terminal (name)
  4477.      char *name;
  4478. {
  4479.   if (interactive_shell && !no_line_editing)
  4480.     rl_reset_terminal (get_string_value ("TERM"));
  4481. }
  4482.  
  4483. void
  4484. sv_hostname_completion_file (name)
  4485.      char *name;
  4486. {
  4487.   hostname_list_initialized = 0;
  4488. }
  4489. #endif /* READLINE */
  4490.  
  4491. #if defined (HISTORY)
  4492. /* What to do after the HISTSIZE variable changes.
  4493.    If there is a value for this variable (and it is numeric), then stifle
  4494.    the history.  Otherwise, if there is NO value for this variable,
  4495.    unstifle the history. */
  4496. void
  4497. sv_histsize (name)
  4498.      char *name;
  4499. {
  4500.   char *temp = get_string_value (name);
  4501.  
  4502.   if (temp && *temp)
  4503.     {
  4504.       int num;
  4505.       if (sscanf (temp, "%d", &num) == 1)
  4506.     {
  4507.       stifle_history (num);
  4508.       if (history_lines_this_session > where_history ())
  4509.         history_lines_this_session = where_history ();
  4510.     }
  4511.     }
  4512.   else
  4513.     unstifle_history ();
  4514. }
  4515.  
  4516. /* What to do if the HISTFILESIZE variable changes. */
  4517. void
  4518. sv_histfilesize (name)
  4519.      char *name;
  4520. {
  4521.   char *temp = get_string_value (name);
  4522.  
  4523.   if (temp && *temp)
  4524.     {
  4525.       int num;
  4526.       if (sscanf (temp, "%d", &num) == 1)
  4527.     {
  4528.       history_truncate_file (get_string_value ("HISTFILE"), num);
  4529.       if (num <= history_lines_in_file)
  4530.         history_lines_in_file = num;
  4531.     }
  4532.     }
  4533. }
  4534.  
  4535. /* What to do after the HISTORY_CONTROL variable changes. */
  4536. void
  4537. sv_history_control (name)
  4538.      char *name;
  4539. {
  4540.   char *temp = get_string_value (name);
  4541.  
  4542.   history_control = 0;
  4543.  
  4544.   if (temp && *temp)
  4545.     {
  4546.       if (strcmp (temp, "ignorespace") == 0)
  4547.     history_control = 1;
  4548.       else if (strcmp (temp, "ignoredups") == 0)
  4549.     history_control = 2;
  4550.       else if (strcmp (temp, "ignoreboth") == 0)
  4551.     history_control = 3;
  4552.     }
  4553. }
  4554.  
  4555. /* What to do after the COMMAND_ORIENTED_HISTORY variable changes. */
  4556. void
  4557. sv_command_oriented_history (name)
  4558.      char *name;
  4559. {
  4560.   SET_INT_VAR (name, command_oriented_history);
  4561. }
  4562.  
  4563. /* Setting/unsetting of the history expansion character. */
  4564.  
  4565. void
  4566. sv_histchars (name)
  4567.      char *name;
  4568. {
  4569.   char *temp = get_string_value (name);
  4570.  
  4571.   if (temp)
  4572.     {
  4573.       history_expansion_char = *temp;
  4574.       if (temp[0] && temp[1])
  4575.     {
  4576.       history_subst_char = temp[1];
  4577.       if (temp[2])
  4578.           history_comment_char = temp[2];
  4579.     }
  4580.     }
  4581.   else
  4582.     {
  4583.       history_expansion_char = '!';
  4584.       history_subst_char = '^';
  4585.       history_comment_char = '#';
  4586.     }
  4587. }
  4588. #endif /* HISTORY */
  4589.  
  4590. void
  4591. sv_allow_null_glob_expansion (name)
  4592.      char *name;
  4593. {
  4594.   SET_INT_VAR (name, allow_null_glob_expansion);
  4595. }
  4596.  
  4597. /* If the variable exists, then the value of it can be the number
  4598.    of times we actually ignore the EOF.  The default is small,
  4599.    (smaller than csh, anyway). */
  4600. void
  4601. sv_ignoreeof (name)
  4602.      char *name;
  4603. {
  4604.   SHELL_VAR *tmp_var;
  4605.   char *temp;
  4606.   int new_limit;
  4607.  
  4608.   eof_encountered = 0;
  4609.  
  4610.   tmp_var = find_variable (name);
  4611.   ignoreeof = tmp_var != 0;
  4612.   temp = tmp_var ? value_cell (tmp_var) : (char *)NULL;
  4613.   if (temp)
  4614.     {
  4615.       if (sscanf (temp, "%d", &new_limit) == 1)
  4616.     eof_encountered_limit = new_limit;
  4617.       else
  4618.     eof_encountered_limit = 10; /* csh uses 26. */
  4619.     }
  4620. }
  4621.  
  4622. /* Control whether * matches .files in globbing.  Yechh. */
  4623. int glob_dot_filenames = 0;
  4624.  
  4625. void
  4626. sv_glob_dot_filenames (name)
  4627.      char *name;
  4628. {
  4629.   SET_INT_VAR (name, glob_dot_filenames);
  4630. }
  4631.  
  4632. #if defined (JOB_CONTROL)
  4633. /* Job notification feature desired? */
  4634. void
  4635. sv_notify (name)
  4636.      char *name;
  4637. {
  4638.   SET_INT_VAR (name, asynchronous_notification);
  4639. }
  4640. #endif  /* JOB_CONTROL */
  4641.  
  4642. /* If the variable `nolinks' exists, it specifies that symbolic links are
  4643.    not to be followed in `cd' commands. */
  4644. void
  4645. sv_nolinks (name)
  4646.      char *name;
  4647. {
  4648.   SET_INT_VAR (name, no_symbolic_links);
  4649. }
  4650.  
  4651. /* Don't let users hack the user id variables. */
  4652. void
  4653. sv_uids (name)
  4654.      char *name;
  4655. {
  4656.   char *buff;
  4657.   register SHELL_VAR *v;
  4658.  
  4659.   buff = itos (current_user.uid);
  4660.   v = find_variable ("UID");
  4661.   if (v)
  4662.     v->attributes &= ~att_readonly;
  4663.  
  4664.   v = bind_variable ("UID", buff);
  4665.   v->attributes |= (att_readonly | att_integer);
  4666.   free (buff);
  4667.  
  4668.   buff = itos (current_user.euid);
  4669.   v = find_variable ("EUID");
  4670.   if (v)
  4671.     v->attributes &= ~att_readonly;
  4672.  
  4673.   v = bind_variable ("EUID", buff);
  4674.   v->attributes |= (att_readonly | att_integer);
  4675.   free (buff);
  4676. }
  4677.  
  4678. #if defined (GETOPTS_BUILTIN)
  4679. void
  4680. sv_optind (name)
  4681.      char *name;
  4682. {
  4683.   char *tt = get_string_value ("OPTIND");
  4684.   int s = 0;
  4685.  
  4686.   if (tt && *tt)
  4687.     {
  4688.       s = atoi (tt);
  4689.  
  4690.       /* According to POSIX, setting OPTIND=1 resets the internal state
  4691.      of getopt (). */
  4692.       if (s < 0 || s == 1)
  4693.     s = 0;
  4694.     }
  4695.   getopts_reset (s);
  4696. }
  4697.  
  4698. void
  4699. sv_opterr (name)
  4700.      char *name;
  4701. {
  4702.   char *tt = get_string_value ("OPTERR");
  4703.   int s = 1;
  4704.  
  4705.   if (tt && *tt)
  4706.     s = atoi (tt);
  4707.   opterr = s;
  4708. }
  4709. #endif /* GETOPTS_BUILTIN */
  4710.  
  4711. void
  4712. sv_strict_posix (name)
  4713.      char *name;
  4714. {
  4715.   SET_INT_VAR (name, posixly_correct);
  4716.   if (posixly_correct)
  4717.     interactive_comments = 1;
  4718. #if defined (READLINE)
  4719.   posix_readline_initialize (posixly_correct);
  4720. #endif /* READLINE */
  4721. }
  4722.